<?php

namespace app\order\logic;

use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;
use app\api\logic\ApiOrderLogic;
use app\api\logic\ApiOrdercheckLogic;
use app\api\logic\FreightLogic;
use app\api\logic\FeiShuTalkLogic;
use app\order\logic\OrderSourceLogic;
use app\order\logic\CheckbillLogic;
use app\api\logic\ShopyLogic;
use app\order\logic\OrderReportSkuLogic;
use app\api\logic\FeiShuMessageLogic;
use app\data\util\HttpUtil;
use app\api\logic\CheckLogic;
use app\purchase\logic\PlanSuggestLogic;

class OrderLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\order\model\Order();
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $shop_id = $params['shop_id'] ?? "";
        $order_id = $params['order_id'] ?? "";
        $financial_status = $params['financial_status'] ?? "";
        $fulfillment_status = $params['fulfillment_status'] ?? "";
        $is_disputeapi_status = $params['is_disputeapi_status'] ?? "";
        $LogisticsStatus = $params['LogisticsStatus'] ?? "";
        $keyword = $params['keyword'] ?? "";
        $create_time = $params['create_time'] ?? "";

        $where = [];
        if (!empty($shop_id)) {
            $where[] = ['shop_id', '=', $shop_id];
        }
        if (!empty($order_id)) {
            $order_ids = explode("\n", trim($order_id));
            $order_ids_new = array_map('trim', array_filter($order_ids, function($v) {  
                return !empty(trim($v));  
            }));
            if (!empty($order_ids_new)) {
                $where[] = ['order_id|name|order_number', 'in', $order_ids_new];
            }
        }
        if (!empty($financial_status)) {
            $where[] = ['financial_status', '=', $financial_status];
        }
        if (!empty($fulfillment_status)) {
            $where[] = ['fulfillment_status', '=', $fulfillment_status];
        }

        if ($is_disputeapi_status){
             //批量获取争议状态id;
            $disputeapi_status_arr = self::get_disputeapi_status($is_disputeapi_status);
            if($disputeapi_status_arr){
                $where[]               = ['order_id', 'in', $disputeapi_status_arr];
            }
        }
        if ($LogisticsStatus){
            $where[] = ['LogisticsStatus', '=', $LogisticsStatus];
        }

        if (!empty($keyword)) {
            $data = $this->KeywordSearch($where,$limit,$keyword);
            return json(DefaultResponse(200, true, '获取成功', $data));
        }

        if($create_time){
            $where[]     = ['createtime', '>=', strtotime($create_time['0'])];
            $where[]     = ['createtime', '<=', strtotime($create_time['1']) + 3600*24-1];
        }

        $list = $this->model
            ->where($where)
            ->order('createtime desc')
            ->paginate($limit);
        $lists = $list->items();
        $order_ids = array_column($lists,'order_id');
        //批量获取店铺信息;
        $shop_list     = Db::name('shops')->field('id as shop_id,name')->select()->toArray();
        $shop_list_map = array_column($shop_list,null,'shop_id');
        //批量运营信息;
        $system_admin_list     = Db::name('system_admin')->field('id as admin_id,nickname')->select()->toArray();
        $system_admin_map = array_column($system_admin_list,null,'admin_id');
        
        //批量获取运费;
        $order_ids     = Db::name('order_achievement')
            ->field('
                order_id,
                freight,freight_weight,
                estimate_freight,estimate_weight,disputeapi_status,admin_id
            ')
            ->whereIn('order_id',$order_ids)
            ->select();
        $order_ids     = objectToArray($order_ids);
        $order_ids_map = array_column($order_ids,null,'order_id');
        foreach ($lists as $k=>$v) {
            $shop_info = $shop_list_map[$v['shop_id']]??[];
            $ship_info = $order_ids_map[$v['order_id']]??[];
            $lists[$k]['createtime'] = date('Y-m-d H:i', $v['createtime']);
            
            $admin_info = $system_admin_map[$ship_info['admin_id']]??[];
            $lists[$k]['nickname'] = $admin_info['nickname']??'';
            
            $lists[$k]['shop_name'] = $shop_info['name']??'';
            $lists[$k]['freight']        = $ship_info['freight'] ? getRes($ship_info['freight']):'';
            $lists[$k]['freight_weight'] = $ship_info['freight_weight'] ? intval($ship_info['freight_weight']) : 0;
            $lists[$k]['estimate_freight'] = $ship_info['estimate_freight']??0;
            $lists[$k]['estimate_weight'] = $ship_info['estimate_weight']??0;
            $lists[$k]['disputeapi_status'] = $ship_info['disputeapi_status']??"";

            $lists[$k]['LogisticsStatus'] = $this->switch_LogisticsStatus($v['LogisticsStatus']);
        }
        
        $data = [
            'list'  => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    public function switch_LogisticsStatus($LogisticsStatus)
    {
        switch ($LogisticsStatus) {
            case 'InTransit_Other':
                return "在途";
                break;
            case 'InTransit_PickedUp':
                return "在途-已揽收";
                break;
            case 'InfoReceived':
                return "已收到信息";
                break;
            case 'OutForDelivery_Other':
                return "出门投递-其它";
                break;
            case 'Delivered_Other':
                return "已妥投-其它";
                break;
            case 'InTransit_CustomsReleased':
                return "在途-海关放行";
                break;
            case 'InTransit_CustomsProcessing':
                return "在途-海关处理中";
                break;
            case 'Exception_Delayed':
                return "异常-延迟";
                break;
            case 'AvailableForPickup_Other':
                return "到达待取-其它";
                break;
            case 'Exception_Returning':
                return "异常-退回中";
                break;
            case 'DeliveryFailure_InvalidAddress':
                return "投递失败-地址无效";
                break;
            case 'InTransit_Departure':
                return "在途-离境";
                break;
            case 'DeliveryFailure_Other':
                return "投递失败-其它";
                break;
            case 'DeliveryFailure_NoBody':
                return "投递失败-没人";
                break;
            case 'Exception_Returned':
                return "异常-已退回";
                break;
            case 'Exception_NoBody':
                return "异常-没人";
                break;
            default:
                return $LogisticsStatus;
        }
    }
    


    /**
    * @desc    关键字搜索
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function KeywordSearch($where,$limit,$keyword)
    {
        $keyword = '%' . $keyword . '%';
        $where_keyword[] = ['
            a.name|
            a.order_number|
            a.tracking_number|
            d.name|
            c.email', 'like', $keyword
        ];

        $list = $this->model
            ->field('a.*,b.name as shop_name')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->join('qu_order_customer c','c.order_id = a.order_id', 'left')
            ->join('qu_order_billing d','d.order_id = a.order_id', 'left')
            ->where($where)
            ->where($where_keyword)
            ->paginate($limit);
        $lists = $list->items();
        foreach ($lists as $k=>$v) {
            $lists[$k]['createtime'] = date('Y-m-d H:i', $v['createtime']);            
        }
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return $data;
    }


    private function get_disputeapi_status($is_disputeapi_status){
            $order_ids = [];
            switch($is_disputeapi_status){
                case "1":
                    $order_ids = Db::name('order_achievement')->where('disputeapi_status','审核中')->column('order_id');
                    break;
                case "2":
                    $order_ids = Db::name('order_achievement')->where('disputeapi_status','争议输')->column('order_id');
                    break;
                case "3":
                    $order_ids = Db::name('order_achievement')->where('disputeapi_status','其他')->column('order_id');
                    break;
                case "4":
                    $order_ids = Db::name('order_achievement')->where('disputeapi_status','待处理')->column('order_id');
                    break;
                case "5":
                    $order_ids = Db::name('order_achievement')->where('disputeapi_status','争议赢')->column('order_id');
                    break;
            }
            return $order_ids;
    }


    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单编号', 'name'];
        $header[] = ['支付金额', 'total_price'];
        $header[] = ['支付渠道', 'payment_gateway_names'];
        $header[] = ['客户名称', 'first_name'];
        $header[] = ['客户名称', 'last_name'];
        $header[] = ['订单创建时间', 'created_at'];
        $header[] = ['物流状态', 'LogisticsStatus'];
        $header[] = ['发货状态', 'fulfillment_status'];
        $header[] = ['物流单号', 'tracking_number'];
        
        $tableName = $this->model->getName();

        $limit = $params['limit'] ?? 10;
        $shop_id = $params['shop_id'] ?? "";
        $order_id = $params['order_id'] ?? "";
        $financial_status = $params['financial_status'] ?? "";
        $fulfillment_status = $params['fulfillment_status'] ?? "";
        $name = $params['name'] ?? "";
        $is_disputeapi_status = $params['is_disputeapi_status'] ?? "";
        $LogisticsStatus = $params['LogisticsStatus'] ?? "";
        $keyword = $params['keyword'] ?? "";
        $create_time = $params['create_time'] ?? "";

        $where = [];
        if (!empty($shop_id)) {
            $where[] = ['shop_id', '=', $shop_id];
        }
        if (!empty($financial_status)) {
            $where[] = ['financial_status', '=', $financial_status];
        }
        if (!empty($fulfillment_status)) {
            $where[] = ['fulfillment_status', '=', $fulfillment_status];
        }

        if($create_time){
            $where[]     = ['createtime', '>=', strtotime($create_time['0'])];
            $where[]     = ['createtime', '<=', strtotime($create_time['1']) + 3600*24-1];
        }
        
        if ($LogisticsStatus){
            $where[] = ['LogisticsStatus', '=', $LogisticsStatus];
        }

        if (!empty($keyword)) {
            $data = $this->KeywordSearch($where,$limit,$keyword);
            $list = $data['list'];
        }else{
            $list = $this->model
                ->field('a.name,a.total_price,a.payment_gateway_names,b.name as shop_name,c.first_name,c.last_name,
                    a.created_at,
                    a.LogisticsStatus,
                    a.tracking_number,
                    a.fulfillment_status
                ')
                ->alias('a')
                ->join('qu_shops b','b.id = a.shop_id', 'left')
                ->join('qu_order_customer c','c.order_id = a.order_id', 'left')
                ->where($where)
                ->select()
                ->toArray();
        }

        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    public function add($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;
        $result = $this->model->insert($data);
        if ($result !== false) {
            return json(DefaultResponse(200, true, '添加成功!', null));
        } else {
            return json(DefaultResponse(201, false, '添加失败!', null));
        }
    }

    public function find($order_id)
    {
        $row = Db::name('order')->where('order_id',$order_id)->find();
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        //附加信息
        $shops = Db::name('shops')->where('id',$row['shop_id'])->find();
        $order_append = Db::name('order_append')->where('order_id',$row['order_id'])->find();
        $order_customer = Db::name('order_customer')->where('order_id',$row['order_id'])->find();
        if(empty($order_customer)){
            $order_customer = [
                'email' => "",
                'first_name' => "",
                'last_name' => "",
                'phone' => "",
                'created_at' => "",
            ];
        }
        //旧的物流轨迹
        // $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$row['order_id'])->select()->toarray();
        $order_info = Db::name('order_info')->where('order_id',$row['order_id'])->select()->toarray();
        $order_refunds = Db::name('order_refunds')->where('order_id',$row['order_id'])->select()->toarray();
        $order_transactions = Db::name('order_transactions')->where('order_id',$row['order_id'])->select()->toarray();
        $order_achievement = Db::name('order_achievement')->where('order_id',$row['order_id'])->find();
        // $order_billing = Db::name('order_billing')->where('order_id',$row['order_id'])->find();
        // $order_shipping = Db::name('order_shipping')->where('order_id',$row['order_id'])->find();
        //新的物流轨迹
        $order_track = Db::name('order_track')->where('order_id',$row['order_id'])->order('create_time desc')->select()->toarray();

        $row['order_append'] = $order_append;
        $row['order_customer'] = $order_customer;
        $row['order_fulfillments'] = $order_track;
        $row['order_info'] = $order_info;
        $row['order_refunds'] = $order_refunds;
        $row['order_transactions'] = $order_transactions;
        $row['order_achievement'] = $order_achievement;
        // $row['order_billing'] = $order_billing;
        // $row['order_shipping'] = $order_shipping;
        $row['shops'] = $shops;

        //新增客服会话
        // $order_transactions = Db::name('order_transactions')->where('order_id',$row['order_id'])->select()->toarray();
        //新增转单号
        $tracking_number = $order_achievement['tracking_number'] ?? "";
        if (!empty($tracking_number)){
            $yuan_subsegment_4px = db::name('yuan_subsegment_4px')->where('waybill_no',$tracking_number)->find();
            $tracking_number = $yuan_subsegment_4px['waybill_no_new'] ?? "";
        }
        if (!empty($tracking_number)){
            $yuan_subsegment_4px = db::name('yuan_subsegment_dyy')->where('waybill_no',$tracking_number)->find();
            $tracking_number = $yuan_subsegment_4px['waybill_no_new'] ?? "";
        }
        if (empty($tracking_number)){ 
            $row['tracking_number_new'] = "暂无";
        }else{
            $row['tracking_number_new'] = $tracking_number;
        }
        //新增转单号结束

        return json(DefaultResponse(200, true, '获取成功', $row));
    }

    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $id = $data['id'];
        $row = $this->model->find($id);
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        $result = false;

        try {
            $result = $row->save($data);
            if ($result) {
                return json(DefaultResponse(201, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(201, false, '更新成功!', null));
    }
    
    
    //临时洗数据-----test
    public function test1(){

        $list =  Db::name('test')
            ->where('status',0)
            ->order('id','desc')
            ->select()
            ->toarray();

        $count =  Db::name('test')
            ->where('status',0)
            ->count();

        $executedCount = 0;
        foreach ($list as $k=>$v) {
            $where = [];
            $where[]  = ['c.createtime', '>=', 1735660800];
            $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
            $where[] = ['a.is_seel', '<>',1];
            $where[] = ['a.sku','=',$v['email']];
            $list = Db::name('order_skuinfo')
                ->field('
                sum(a.realcount) as skuquantity
                ')
                ->alias('a')
                ->join('qu_order c','a.order_id = c.order_id', 'left')
                ->where($where)
                ->select()->toarray();
            $skuquantity = $list[0]['skuquantity'] ?? 0;
            $update2 = [
                'status'=>1,
                'order_id'=>$skuquantity,
            ];
            Db::name('test')->where('id',$v['id'])->update($update2);

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }
    //临时洗数据-----test
    public function test2(){

        $list =  Db::name('test')
            ->where('status',1)
            ->order('id','desc')
            ->select()
            ->toarray();

        $count =  Db::name('test')
            ->where('status',1)
            ->count();

        $executedCount = 0;
        foreach ($list as $k=>$v) {
            //包含字符串
            if(strpos($v['email'],'-') !== false){
                $sku = explode('-',$v['email']);
                $sku[0] = $sku[0] ?? '';
                $sku[2] = $sku[2] ?? '';
                $msg = $sku[0] ."-". $sku[2];
                $update2 = [
                    'status'=>2,
                    'msg'=>$msg,
                ];
                Db::name('test')->where('id',$v['id'])->update($update2);
            }

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }
    
    //临时洗数据-----test
    public function test(){
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        $query_date = [
            'start_time'  => $start_time,
            'end_time' => $end_time,
            'admin_id' => 85,
        ];
        $where = [];
        $where[]  = ['createtime', '>=', $query_date['start_time']];
        $where[]  = ['createtime', '<=', $query_date['end_time']];
        $where[]  = ['shop_id', '=', 17];
        $where[]  = ['admin_id', '=', $query_date['admin_id']];
        // halt($where);
        //纠错
        // $count = Db::name('order_achievement')
        //     ->where($where)
        //     ->count();
        // halt($count);
        // $update1['source'] = "";
        // $update1['admin_id'] = "";
        // $update2 = Db::name('order_achievement')
        //     ->where($where)
        //     ->update($update1);
        // halt($update2);

        $list =  Db::name('test')
            ->where('status',0)
            ->order('id','desc')
            ->select()
            ->toarray();
            // ->count();
            // halt($list);

        $count =  Db::name('test')
            ->where('status',0)
            ->count();
        // halt($count);

        $executedCount = 0;
        foreach ($list as $k=>$v) {
            // 匹配规则
            $name = "#".$v['email'];
            $order = Db::name('order')
                ->where('shop_id',17)
                ->where('name',$name)
                ->find();
            if(!empty($order)){
                $update = [
                    'admin_id'=>85,
                ];
                Db::name('order_achievement')->where('order_id',$order['order_id'])->update($update);

                $order_source = Db::name('order_source')->where('order_id',$order['order_id'])->find();
                if(!empty($order_source)){
                    if(empty($order_source['tags'])){
                        $update2['tags'] = '4月孙义翔';
                    }else{
                        $update2['tags'] = $order_source['tags'].',4月孙义翔';
                    }
                    Db::name('order_source')->where('order_id',$order['order_id'])->update($update2);
                }
            }
            $update2 = [
                'status'=>1,
            ];
            Db::name('test')->where('id',$v['id'])->update($update2);

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }

    
    //复制产品信息到订单表
    public function CopyProductInformation(){
        $count =  Db::name('order_varient_log')
            ->where('new_varient_id',0)
            ->count();
        // halt($count);

        //old_varient_id = new_varient_id条件
        $sql = "SELECT * FROM `qu_order_varient_log` WHERE `new_varient_id` = `old_varient_id` ORDER BY `id` ASC";
        $list = Db::query($sql);
        // halt($list);
        // foreach ($list as $k=>$v) {
        //     $update = [
        //         'new_varient_id'=>0,
        //     ];
        //     Db::name('order_varient_log')->where('id',$v['id'])->update($update);
        //     echo PHP_EOL . $k . '-----' . $v['id'] . PHP_EOL;
        // }

        $list =  Db::name('order_varient_log')
            ->where('new_varient_id',0)
            ->order('id desc')
            ->select()
            ->toarray();
            // halt($list);
        $executedCount = 0;
        foreach ($list as $k=>$v) {
            // 匹配规则
            // $order = Db::name('order')
            //     ->where('shop_id',$v['shop_id'])
            //     ->where('order_id',$v['order_id'])
            //     ->find();
            $order['order_id'] = $v['order_id'];
            if(!empty($order)){
                $order_info = Db::name('order_info')
                    ->where('order_id',$order['order_id'])
                    ->where('sku',$v['old_sku'])
                    ->find();
                if(empty($order_info)){
                    continue;
                }
                $order_info_new = Db::name('order_info')
                    ->where('shop_id',$v['shop_id'])
                    ->where('variant_id',"<>",$order_info['variant_id'])
                    ->where('sku',$v['old_sku'])
                    ->find();
                $update = [
                    'order_id'=>$order['order_id'],
                    'new_sku'=>$v['old_sku'],
                    'old_varient_id'=>$order_info['variant_id'] ?? 0,
                    'new_varient_id'=>$order_info_new['variant_id'] ?? 0,
                ];
                // halt($update);
                Db::name('order_varient_log')->where('id',$v['id'])->update($update);
            }

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }

    //临时洗数据-----历史sku更新到仓库
    public function skuSynthesis(){
        $count =  Db::name('warehouse_goodsshelves')
            ->count();
        // halt($count);
        $list =  Db::name('warehouse_goodsshelves')
            ->field('id,name')
            ->select()
            ->toarray();
            // halt($list);
        $executedCount = 0;
        foreach ($list as $k=>$v) {
            // 匹配规则
            $skus = Db::name('warehouse_goodsshelvesinfo')
                ->field('sku')
                ->where('name',$v['name'])
                ->select()->toarray();
            $skus = array_column($skus,'sku');
            if(count($skus) > 1){
                $update = [
                    'sku'=>implode(',',$skus),
                ];
                Db::name('warehouse_goodsshelves')->where('id',$v['id'])->update($update);
            }
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }
    //临时洗数据-----匹配发货的sku是否有库存
    public function DoesSkuHaveInventory(){
        $list =  Db::name('order_shopify_list')
            ->field('id,sku')
            ->group('order_id')
            ->where('create_time',">=","2024-07-13 10:35:11")
            ->where('create_time',"<=","2024-07-13 17:35:11")
            // ->where('ship_status',"<",8)
            // ->where('msg',1)
            ->select()
            ->toarray();
            // ->count();
            // halt($list);
        $count = 900;
        $executedCount = 0;
        foreach ($list as $k=>$v) {
            // 匹配规则
            $this->MatchingRules($v);

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }

    /**
    * 匹配规则
    * @param array params
    */
    public function MatchingRules($v)
    {
        $sku = $v['sku'];
        $id = $v['id'];
        if(!empty($sku)){
            $pos = strpos($sku, ',');
            if($pos !== false){
                $sku_arr = explode(',',$sku);
                $SkuRulesArrays = [];
                foreach ($sku_arr as $ks=>$vs) {
                    // 匹配多个sku规则
                    $SkuRulesArray = $this->MatchMultipleSkuRules($vs);
                    if(!empty($SkuRulesArray)){
                        $SkuRulesArrays[] = $SkuRulesArray;
                    }else{
                        $SkuRulesArrays = [];
                        break;
                    }
                }
                // halt($SkuRulesArrays);
                
                if(!empty($SkuRulesArrays)){
                    $Whether = $this->Whether($SkuRulesArrays);
                    //如果同仓库都有库存则代表成功
                    if(!empty($Whether)){
                        $this->RepresentativeSuccess($Whether,$sku_arr,$id);
                    }else{
                        $update = [];
                        $update['msg'] = 3;
                        Db::name('order_shopify_list')
                            ->where('id',$id)
                            ->update($update);
                    }
                }
            }else{
                // 匹配单个sku规则
                $this->MatchASingleSkuRule($sku,$id);
            }
        }
        return true;
    }
    
    /**
    * 匹配单个sku规则
    * @param array params
    */
    public function MatchASingleSkuRule($sku,$id)
    {
        $pos = strpos($sku, '-');
            if($pos !== false){
                $sku_arr = explode('-',$sku);
                $newsku = $sku_arr[0]."-".$sku_arr[1]."-".$sku_arr[2];
                $newsku_num = $sku_arr[3] ?? 1;
                $inventory_hwc = Db::name('inventory_hwc')
                    ->where('sku',$newsku)
                    ->where('new_quantity',">=",$newsku_num)
                    ->find();
                if(!empty($inventory_hwc)){
                    $update = [];
                    $update['ship_status'] = 8;
                    $update['warehouse_id_plan'] = $inventory_hwc['warehouse_id'];
                    $update['msg'] = 2;
                    Db::name('order_shopify_list')
                        ->where('id',$id)
                        ->update($update);
                        
                    $update2 = [];
                    $update2['new_quantity'] = $inventory_hwc['new_quantity'] - 1;
                    $inventory_hwc = Db::name('inventory_hwc')
                        ->where('id',$inventory_hwc['id'])
                        ->update($update2);
                    return true;
                }else{
                    $update = [];
                    $update['msg'] = 3;
                    Db::name('order_shopify_list')
                        ->where('id',$id)
                        ->update($update);
                }
            }
    }

    /**
    * 匹配多个sku规则
    * @param array params
    */
    public function MatchMultipleSkuRules($sku)
    {
        $pos = strpos($sku, '-');
        if($pos !== false){
            $sku_arr = explode('-',$sku);
            $newsku = $sku_arr[0]."-".$sku_arr[1]."-".$sku_arr[2];
            $newsku_num = $sku_arr[3] ?? 1;
            $inventory_hwc = Db::name('inventory_hwc')
                ->field('warehouse_id')
                ->where('sku',$newsku)
                ->where('new_quantity',">=",$newsku_num)
                ->select();
            if(!empty($inventory_hwc)){
                return $inventory_hwc;
            }
        }
        return [];
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function Whether($SkuRulesArray)
    {
        $warehouseIds = [];
        foreach ($SkuRulesArray as $group) {  
            foreach ($group as $item) {  
                if (isset($item['warehouse_id'])) {  
                    $warehouseIds[] = $item['warehouse_id'];  
                }
            }  
        }  
        // 去除重复的warehouse_id 
        $targetIds = []; 
        if(!empty($warehouseIds)){
            $targetIds = array_unique($warehouseIds); 
        }
        $targetIdsNew = 0;
        $allContainTarget = true;  
        foreach ($targetIds as $targetId) {  
            foreach ($SkuRulesArray as $collection) {  
                foreach ($collection as $item) {  
                    if (!isset($item['warehouse_id']) && $item['warehouse_id'] !== $targetId) {  
                        $allContainTarget = false;  
                    }  
                }
            }
            if ($allContainTarget) {  
                $targetIdsNew = $targetId;
                break;
            }
        }
        return $targetIdsNew;
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function RepresentativeSuccess($Whether,$sku_arr,$id)
    {
        foreach ($sku_arr as $ks=>$vs) {
            $pos = strpos($vs, '-');
            if($pos !== false){
                $sku_arr = explode('-',$vs);
                $newsku = $sku_arr[0]."-".$sku_arr[1]."-".$sku_arr[2];
                $newsku_num = $sku_arr[3] ?? 1;

                $inventory_hwc = Db::name('inventory_hwc')
                    ->where('sku',$newsku)
                    ->where('warehouse_id',$Whether)
                    ->where('new_quantity',">=",$newsku_num)
                    ->find();

                if(!empty($inventory_hwc)){
                    $update = [];
                    $update['ship_status'] = 8;
                    $update['warehouse_id_plan'] = $inventory_hwc['warehouse_id'];
                    $update['msg'] = 2;
                    Db::name('order_shopify_list')
                        ->where('id',$id)
                        ->update($update);
                        
                    $update2 = [];
                    $update2['new_quantity'] = $inventory_hwc['new_quantity'] - 1;
                    $inventory_hwc = Db::name('inventory_hwc')
                        ->where('id',$inventory_hwc['id'])
                        ->update($update2);
                }
                    
            }
        }

        return true;
    }


    //订单分配标签为空的情况
    public function CompleteOrderSource(){
        $count = Db::name('order_source')
            ->where('tag_source',"=","")
            ->count();
        echo PHP_EOL .'tag_source修改条数有：'.$count;
        if(!empty($count)){
            $update['tag_source'] = 'LabelIsEmpty';
            $update['tag_campaign'] = 'LabelIsEmpty';
            $updates = Db::name('order_source')
                ->where('tag_source',"=","")
                ->update($update);
            echo PHP_EOL . "tag_source已修改:" . $updates . '条';
        }
        $count = Db::name('order_source')
            // ->where('tag_campaign',"=","")
            ->where('tag_campaign',"=",null)
            ->count();
        echo PHP_EOL .'tag_campaign修改条数有：'.$count;
        if(!empty($count)){
            $update['tag_source'] = 'LabelIsEmpty';
            $update['tag_campaign'] = 'LabelIsEmpty';
            $updates = Db::name('order_source')
                // ->where('tag_campaign',"=","")
                ->where('tag_campaign',"=",null)
                ->update($update);
            echo PHP_EOL . "tag_campaign已修改:" . $updates . '条';
        }
        echo PHP_EOL . "tag_source和tag_campaign已修改完成" . PHP_EOL;
    }

    //检查遗漏
    public function CheckForMissedOrders(){
        //默认为暂无争议
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        // halt($date_msg);
        
        $where = [];
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 

        $count = Db::name('order_achievement')
            ->where('disputeapi_status',"=","")
            ->count();
        echo PHP_EOL . "默认为暂无争议-".$count."条数据，开始操作" . PHP_EOL;
        if(!empty($count)){
            $update = [];
            $update['disputeapi_status'] = '暂无争议';
            Db::name('order_achievement')
                ->where('disputeapi_status',"=","")
                ->update($update);
            echo PHP_EOL . "默认为暂无争议-完成操作" . PHP_EOL;
        }

        //qu_order_source重复
        $count = Db::name('order_source')
            ->where('order_id',">",0)
            ->group('order_id')
            ->having('COUNT(*) > 1')
            ->count();
        echo PHP_EOL . "order_source重复-开始操作" . PHP_EOL;
        if(!empty($count)){
            $duplicates = Db::name('order_source')
                ->field('order_id, COUNT(*) as num_duplicates')
                ->where('order_id',">",0)
                ->group('order_id')
                ->having('COUNT(*) > 1')
                ->select()
                ->toArray();
            $executedCount = 0;
            foreach ($duplicates as $duplicate) {
                $keepId = Db::name('order_source')
                    ->where('order_id', $duplicate['order_id'])
                    ->min('id');
                // 删除其他所有ID的记录
                Db::name('order_source')
                    ->where('order_id', $duplicate['order_id'])
                    ->where('id', '<>', $keepId) // 排除要保留的记录
                    ->delete();
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "order_source重复总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        } 

        //qu_order_source遗漏
        $count = Db::name('order')
            ->field('o.order_id,o.shop_id,o.created_at')
            ->alias('o')
            ->join('qu_order_source a','o.order_id = a.order_id ', 'left')
            ->where("a.order_id IS NULL")
            // ->where("o.shop_id","=",17)
            ->count();
            // halt($count);
            
        echo PHP_EOL . "order_source遗漏-开始操作" . PHP_EOL;
        if(!empty($count)){
            $list = Db::name('order')
                ->field('o.order_id,o.shop_id,o.created_at')
                ->alias('o')
                ->join('qu_order_source a','o.order_id = a.order_id ', 'left')
                ->where("a.order_id IS NULL")
                // ->where("o.shop_id","=",17)
                ->order('o.created_at DESC')
                ->select()
                ->toarray();
            $executedCount = 0;
            foreach ($list as $k=>$v) {
                $insert = $this->CompleteOrderSources($v['order_id'],1);
                Db::name('order_source')->insert($insert);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "order_source总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
        //qu_order_achievement遗漏
        $count = Db::name('order')
            ->field('o.order_id,o.shop_id,o.created_at')
            ->alias('o')
            ->join('qu_order_achievement a','o.order_id = a.order_id ', 'left')
            ->where("a.order_id IS NULL")
            ->count();
        echo PHP_EOL . "order_achievement遗漏-开始操作" . PHP_EOL;
        if(!empty($count)){
            $list = Db::name('order')
                ->field('o.order_id,o.shop_id,o.created_at')
                ->alias('o')
                ->join('qu_order_achievement a','o.order_id = a.order_id ', 'left')
                ->where("a.order_id IS NULL")
                ->order('o.created_at DESC')
                ->select()
                ->toarray();
            $executedCount = 0;
            foreach ($list as $k=>$v) {
                $insert = $this->CompleteOrderSources($v['order_id'],2);
                Db::name('order_achievement')->insert($insert);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "order_achievement总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
        echo PHP_EOL . "order_achievement遗漏-结束操作" . PHP_EOL;
        //order_source的sku为空
        $count = Db::name('order_source')
            ->where('skus',"=","")
            ->count();
        echo PHP_EOL . "order_source的sku为空-开始操作" . PHP_EOL;
        if(!empty($count)){
            $sources = Db::name('order_source')
                ->field('id,order_id')
                ->where('skus',"=","")
                ->order('id desc')
                ->select()
                ->toArray();
            $executedCount = 0;
            $executedCountsu = 0;
            foreach ($sources as $source) {
                $skus = Db::name('order_achievement')
                    ->field('sku')
                    ->where('order_id', $source['order_id'])
                    ->find();
                if(!empty($skus['sku'])){
                    $update = [];
                    $update['skus'] = $skus['sku'];
                    Db::name('order_source')->where('order_id',$source['order_id'])->update($update);
                    $executedCountsu++;
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "order_source的sku为空:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . ',成功'.$executedCountsu.'剩余:' . $num . '条' . PHP_EOL;
            }
        }
        $count = Db::name('order_source')
            ->where('shop_id',"=",17)
            ->where('skus',"=",null)
            ->count();
        echo PHP_EOL . "17店铺的order_source的sku为空-开始操作" . PHP_EOL;
        if(!empty($count)){
            $sources = Db::name('order_source')
                ->field('order_id')
                ->where('shop_id',"=",17)
                ->where('skus',"=",null)
                ->select()
                ->toArray();
            $executedCount = 0;
            $executedCountsu = 0;
            foreach ($sources as $source) {
                $skus = Db::name('order_achievement')
                    ->field('sku')
                    ->where('order_id', $source['order_id'])
                    ->find();
                if(!empty($skus['sku'])){
                    $update = [];
                    $update['skus'] = $skus['sku'];
                    Db::name('order_source')->where('order_id',$source['order_id'])->update($update);
                    $executedCountsu++;
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "17店铺的order_source的sku为空:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . ',成功'.$executedCountsu.'剩余:' . $num . '条' . PHP_EOL;
            }
        }
        echo PHP_EOL . "order_source的sku为空-完成操作" . PHP_EOL;
    }

    /**
    * @desc    补全订单来源数据表
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function CompleteOrderSources($order_id,$type)
    {
        $order = Db::name('order')
            ->where('order_id',$order_id)
            ->find();
            
        if(empty($order)){
            $insert = []; 
            return $insert;
        }

        switch ($type) {
            case '1':
                $insert['order_id'] = $order['order_id']; 
                $insert['shop_id'] = $order['shop_id']; 
                $insert['name'] = $order['name'] ?? ""; 
                $insert['total_price'] = $order['total_price']; 
                $insert['financial_status'] = $order['financial_status']; 
                $insert['fulfillment_status'] = $order['fulfillment_status']; 
                $insert['createtime'] = $order['createtime']; 
                $insert['created_at'] = $order['created_at']; 
                break;
            case '2':
                $insert['order_id'] = $order['order_id']; 
                $insert['name'] = $order['name'] ?? "";
                $insert['financial_status'] = $order['financial_status'] ?? "";
                $insert['fulfillment_status'] = $order['fulfillment_status'] ?? "";
                $insert['tracking_number'] = $order['tracking_number'] ?? "";
                $insert['shop_id'] = $order['shop_id'];
                $insert['total_price'] = $order['total_price'] ?? 0;
                if($order['financial_status'] == "refunded"){
                    $insert['total_price'] = 0;
                }
                $insert['refund'] = 0;
                $insert['createtime'] = $this->dateTimeStr($order['created_at']); 
                $insert['tags'] = $order['tags'] ?? "";
                $insert['sku'] = "";
                break;
            default:
        }
        return $insert;
    }
    
    //反馈表新增SPU
    public function AddSpuToFeedbackForm(){
        $count = Db::name('order_info')
            ->where('spu',"")
            ->count();
        // halt($count); 
        $list = Db::name('order_info')
            ->field('id,sku')
            ->where('spu',"")
            ->select()
            ->toarray();
        $executedCount = 0;
        foreach ($list as $k=>$v) {
            $dashPos = strpos($v['sku'], '-');  
            if ($dashPos !== false) {  
                $update = [];
                $update['spu'] = substr($v['sku'], 0, $dashPos);  
                
                Db::name('order_info')
                    ->where('id',$v['id'])
                    ->update($update);
            }

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }

    //计算物流成本
    public function EstimatedCostPerOrder(){
        //物流账单是美金 需要转成人民币
        // $t1       = microtime(true);
        // $ordercheck_logistics = Db::name('ordercheck_logistics')
        //     ->field('id,freight')
        //     ->where('date','2024-08')
        //     ->where('tracking_company_number',3)
        //     ->select()->toarray();
        // $executedCount = 0;
        // foreach ($ordercheck_logistics as $k=>$v) {
        //     $update['freight'] = (float)number_format((float)$v['freight'] * 7.116, 3, '.', '');
        //     Db::name('ordercheck_logistics')
        //         ->where('id',$v['id'])
        //         ->update($update);
        //     $executedCount++;
        //     echo PHP_EOL . "已执行:" . $executedCount . '' . PHP_EOL;
        // }
        // echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;die;
        //物流账单是美金 需要转成人民币--结束
                    
        $t1       = microtime(true);

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        // halt($date_msg);
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked" ,"partial"]];
        // $where[]  = ['shop_id', '=', 17];
// halt($where);
        // $where[]  = ['admin_id', '=', 85]; 
        //清空
        // $update = [];
        // $update['freight'] = 0;
        // $update['freight_status'] = "";
        // $update['estimate_weight'] = 0;
        // $update['estimate_freight'] = 0;
        // $update = Db::name('order_achievement')
        //     ->where($where)
        //     // ->where("freight", '<=', 0)
        //     // ->where('freight_weight',"<=",0)
        //     // ->where('freight_status',"=","预估物流费")
        //     ->update($update);
        //     halt($update);
        //清空

        //汇率
        $dollar    = Db::name('order_exchange')
            ->where(['date' => $date])
            ->value('dollar');
        // halt($dollar);


        $count = Db::name('order_achievement')
            ->where($where)
            // ->where('freight_status',"=","")
            ->where('estimate_freight',"<=",0)
            // ->where('id',"=",1351928)
            ->count();
            // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('order_id,tracking_number,createtime,freight,old_total_price,financial_status')
                ->where($where)
                // ->where('freight_status',"=","")
                ->where('estimate_freight',"<=",0)
                // ->where('id',"=",1351928)
                ->limit(500)
                ->order('id asc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                // halt($v);
                
                //预估物流成本
                $this->add_freight($v,$dollar);
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    //交易api匹配订单时间
    public function OrderBalanceApi(){
        $t1       = microtime(true);

        $count = Db::name('order_balance_api')
            ->where('createtime',0)
            // ->where('payment_gateway_names',"=",null)
            ->where('source_order_id',"<>","")
            ->count();
        // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_balance_api')
                ->field('id,source_order_id')
                ->where('createtime',0)
                // ->where('payment_gateway_names',"=",null)
                // ->where('source_order_id',"<>","")
                // ->paginate([  
                //     'list_rows' => $pageSize,
                //     'page' => $i,
                // ])
                // ->toArray();
                ->limit(500)
                ->order('id asc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                if(empty($v['source_order_id'])){
                    continue;
                }
                
                $order = Db::name('order_achievement')
                    ->where('order_id',$v['source_order_id'])
                    ->find();

                $update = [];
                $order2 = Db::name('order')
                    ->where('order_id',$v['source_order_id'])
                    ->find();
                $update['createtime'] = $order2['createtime'];
                $update['created_at'] = $order2['created_at'];
                    
                if(!empty($order['payment_gateway_names'])){
                    $update['payment_gateway_names'] = $order['payment_gateway_names'] ?? "";
                    Db::name('order_balance_api')
                        ->where('id',$v['id'])
                        ->update($update);
                    $executedCountsu++;
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . ',成功'.$executedCountsu.'条,剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }
    //订单来源匹配number
    public function OrderSourceMatchingNumber(){
        $t1       = microtime(true);

        $count = Db::name('order_source')
            ->where('order_number',"=","")
            ->count();
        // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_source')
                ->field('id,order_id')
                ->where('order_number',"=","")
                ->limit(500)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                if(empty($v['order_id'])){
                    continue;
                }
                $order = Db::name('order')
                    ->where('order_id',$v['order_id'])
                    ->find();
                if(!empty($order['order_number'])){
                    $update['order_number'] = $order['order_number'];
                    Db::name('order_source')
                        ->where('id',$v['id'])
                        ->update($update);
                    $executedCountsu++;
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . ',成功'.$executedCountsu.'条,剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    //SPU纠正成最新的
    public function SpuCorrectedToTheLatestVersion()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $Count     = Db::name('ordercheck_spucost')
            ->field('spu,material')
            ->where('date',$date)
            ->group('spu')
            ->Count();
            // halt($Count);
            
        $ordercheck_spucost     = Db::name('ordercheck_spucost')
            ->field('spu,material')
            ->where('date',$date)
            ->group('spu')
            ->order('material desc')
            ->select()
            ->toArray();
        $executedCount = 0;
        foreach ($ordercheck_spucost as $k=>$v) {
            $spucost = Db::name('ordercheck_spucost_time')
                ->where('spu',$v['spu'])
                ->find();
            
            if(!empty($spucost)){
                $update = [
                    'material' => $spucost['material'],
                ];
                Db::name('ordercheck_spucost')
                    ->where('spu',$v['spu'])
                    ->update($update);
                $executedCount++;
            }
            echo PHP_EOL . "总计要执行条数:" . $Count . '-----' . '修改'.$executedCount.'条' . PHP_EOL;
        }
    }

    

    //每月采购成本
    public function MonthlySpuCost()
    {
        $where = [];

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where[]  = ['c.createtime', '>=', $start_time];
        $where[]  = ['c.createtime', '<=', $end_time]; 
// halt($where);

        // $delete = Db::name('ordercheck_spucost')
        //     ->where('date',$date)
        //     ->delete();
        //     halt($delete);

        // $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        // $where[]  = ['a.spu', '=', "sock04"];
        $lists = Db::name('order_skuinfo')
            ->field('
                a.spu
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.spu')
            ->select()->toarray();
            
        $Count = Db::name('order_skuinfo')
            ->field('
                a.spu
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.spu')
            ->count();
        // halt($lists);
        $executedCount = 0;
        $executedCountadd = 0;
        //批量获取sku图片;
        $spus  = array_column($lists,'spu');

        $date_last = date('Y-m', $start_time - 1);
        $ordercheck_spucost_last     = Db::name('ordercheck_spucost')
            ->field('spu,material')
            ->where('date',$date_last)
            ->whereIn('spu',$spus)
            ->group('spu')
            ->order('material desc')
            ->select()
            ->toArray();
        $ordercheck_spucost     = Db::name('ordercheck_spucost')->field('spu,MAX(material) as material')->whereIn('spu',$spus)->group('spu')->order('material desc')->select()->toArray();
        
        $material_map = array_column($ordercheck_spucost,null,'spu');
        $material_map_last = array_column($ordercheck_spucost_last,null,'spu');

        foreach ($lists as $k=>$v) {
            $lists[$k]['date'] = $date;
            $lists[$k]['timedate'] = $start_time;

            $materials_last = $material_map_last[$v['spu']]??[];
            $lists[$k]['material'] = $materials_last['material']??'';
            if(empty($lists[$k]['material'])){
                $materials = $material_map[$v['spu']]??[];
                $lists[$k]['material'] = $materials['material']??'';
            }

            if($lists[$k]['material'] <= 0.001){
                $product = Db::name('product')
                    ->where('spu',$v['spu'])
                    ->order('purchase_cost desc')
                    ->find();
                if(isset($product) && $product['purchase_cost'] > 0.01){
                    $lists[$k]['material'] = $product['purchase_cost'];
                }
            }
            $spucost = Db::name('ordercheck_spucost')
                ->where('spu',$v['spu'])
                ->where('date',$date)
                ->find();
            $update = $lists[$k];
            
            //如果找不到成本
            if($update['material'] <= 0){
                $product = Db::name('product')
                    ->field('spu,purchase_cost')
                    ->where('spu',$update['spu'])
                    ->find();
                $update['material'] = $product['purchase_cost'] ?? 0;
            }
            
            if(!empty($spucost)){
                // if($spucost['material'] < 1){
                    Db::name('ordercheck_spucost')
                        ->where('spu',$v['spu'])
                        ->where('date',$date)
                        ->update($update);
                // }
                $executedCount++;
            }else{
                Db::name('ordercheck_spucost')->insert($update);
                $executedCountadd++;
            }
            echo PHP_EOL . "总计要执行条数:" . $Count . '-----' . '成功添加'.$executedCountadd.'，修改'.$executedCount.'条' . PHP_EOL;
        }
    }

    /**
    * @desc    发消息通知
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function SendAMessageNotification()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        $msg = "已生成".$date_msg."采购成本月报数据，请核对";
        //飞书消息
        $FeiShuTalkLogic = new FeiShuTalkLogic();
        $FeiShuTalkLogic->send($msg);
        echo "已发送飞书消息通知" . PHP_EOL;
        // 飞书消息---个人消息
        $FeiShuMessageLogic = new FeiShuMessageLogic();
        $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
        $open_id = $system_admin['open_id'] ?? 0;
        if($open_id){
            $datamsg = [
                'message' => $msg,
                'open_id' => $open_id,
            ];
            $FeiShuMessageLogic->send_message($datamsg);
        }
        echo "已发送飞书个人消息通知" . PHP_EOL;
        // 飞书消息---个人消息
        $FeiShuMessageLogic = new FeiShuMessageLogic();
        $system_admin = Db::name('system_admin')->field('open_id')->where('id',18)->find();
        $open_id = $system_admin['open_id'] ?? 0;
        if($open_id){
            $datamsg = [
                'message' => $msg,
                'open_id' => $open_id,
            ];
            $FeiShuMessageLogic->send_message($datamsg);
        }
        echo "已发送飞书个人消息通知" . PHP_EOL;

    }
    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 每月采购成本sku
     * @author zhangheng
     */
    public function MonthlySkuCost()
    {
        $where = [];

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        // halt($date_msg);
        
        $where[]  = ['c.createtime', '>=', $start_time];
        $where[]  = ['c.createtime', '<=', $end_time];

        // $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        // halt($where);
        
        //清空
        // $delete = Db::name('ordercheck_skucost')
        //     ->where('date',$date)
        //     ->delete();
        // halt($delete);
        
        $lists = Db::name('order_info')
            ->field('
                a.sku,a.spu,d.material
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->join('qu_ordercheck_spucost d','d.spu = a.spu', 'left')
            ->where($where)
            ->where('d.date', '=', $date)
            ->where('a.sku',"<>","")
            ->group('a.sku')
            // ->count();
            ->select()->toarray();
            // halt($lists);

        $counts = Db::name('order_info')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->join('qu_ordercheck_spucost d','d.spu = a.spu', 'left')
            ->where($where)
            ->where('d.date', '=', $date)
            ->where('a.sku',"<>","")
            ->group('a.sku')
            ->count();

        $executedCount = 0;
        $executedCountsu = 0;
        foreach ($lists as $k=>$v) {
            
            $lists[$k]['date'] = $date;
            $lists[$k]['timedate'] = $start_time;
            $count = (new ApiOrdercheckLogic())->CountTheNumberOfItems($v);
            $lists[$k]['count'] = $count;
            $lists[$k]['material_total'] = (float)number_format((float)$v['material'] * $count, 3, '.', '');
            $ordercheck_skucost = Db::name('ordercheck_skucost')
                ->where('timedate',$lists[$k]['timedate'])
                ->where('sku',$lists[$k]['sku'])
                ->find();
            if(empty($ordercheck_skucost)){
                Db::name('ordercheck_skucost')->insert($lists[$k]);
                $executedCountsu++;
            }else{
                // $update = $lists[$k];
                // halt($update);
                // Db::name('ordercheck_skucost')
                //     ->where('timedate',$lists[$k]['timedate'])
                //     ->where('sku',$lists[$k]['sku'])
                //     ->update($update);
                    // $executedCountsu++;
            }
            
            $executedCount++;
            echo PHP_EOL . "总计".$counts.",已执行:" . $executedCount . '-----' . '成功修改'.$executedCountsu.'条' . PHP_EOL;
        }
    }

    //SKU价格同步
    public function CompleteTheProcurementCost(){
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $t1       = microtime(true);
        $count = Db::name('ordercheck_skucost')
            // ->where('material',"<=",0.01)
            ->where('date',"=",$date)
            ->count();
        // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('ordercheck_skucost')
                ->field('id,spu,timedate,count,sku')
                // ->where('material',"<=",0.01)
                ->where('date',"=",$date)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            foreach ($list['data'] as $v){
                //继承上个月
                // $date_last = date('Y-m', $start_time - 1);
                // $ordercheck_spucost = Db::name('ordercheck_skucost')
                //     ->where('sku',$v['sku'])
                //     ->where('timedate',$date_last)
                //     ->find();
                // if(isset($ordercheck_spucost['material'])){
                //     echo PHP_EOL . "spu:".$v['spu']."-----".$v['sku']."-----".$ordercheck_spucost['material'];
                // }
                //继承spu
                $ordercheck_spucost['material'] = 0.01;
                if(!empty($ordercheck_spucost['material']) && $ordercheck_spucost['material'] <= 0.01){
                    $ordercheck_spucost = Db::name('ordercheck_spucost')
                        ->where('spu',$v['spu'])
                        ->where('timedate',$v['timedate'])
                        ->find();
                }
                    
                if(!empty($ordercheck_spucost['material']) && $ordercheck_spucost['material'] <= 0.01){
                    $ordercheck_spucost = Db::name('ordercheck_spucost')
                        ->where('spu',$v['spu'])
                        ->order('material desc')
                        ->find();
                }
                if(!empty($ordercheck_spucost['material']) && $ordercheck_spucost['material'] <= 0.01){
                    $product = Db::name('product')
                        ->where('spu',$v['spu'])
                        ->order('purchase_cost desc')
                        ->find();
                        if(isset($product) && $product['purchase_cost'] > 0.01){
                            $ordercheck_spucost['material'] = $product['purchase_cost'];
                        }
                }
                // halt($ordercheck_spucost);
                if(!empty($ordercheck_spucost['material']) && $ordercheck_spucost['material'] > 0.01){
                    $update = [];
                    $update['material'] = (float)$ordercheck_spucost['material'];
                    $update['material_total'] = (float)number_format((int)$v['count']*(float)$update['material'], 3, '.', '');
                    
                    Db::name('ordercheck_skucost')->where('id',$v['id'])->update($update);
                    $executedCountsu++;
                }

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //部分SPU的sku采购价不同
    public function PartialSpuSkusHaveDifferentAdd(){
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $t1       = microtime(true);

        $spus = ['bra37', 'pan64', 'sha226'];//十月
        foreach ($spus as $v) {
            $spucost = Db::name('ordercheck_skucost')
                ->field('spu,sku,material')
                ->where('date',"=",$date)
                ->where('spu',$v)
                ->select()->toarray();
                $skus = [];
                foreach ($spucost as $ks=>$vs) {
                    $skus = $this->DisassembleAttributes($vs['sku'],$skus);
                    $material = $vs['material'] ?? 0;
                }
                if(!empty($skus)){
                    foreach ($skus as $ki=>$vi) {
                        $insert[] = [
                            'spu' => $v,
                            'sku' => $ki,
                            'date' => $date,
                            'material' => $material ?? 0,
                        ];
                    }
                    Db::name('ordercheck_skuchange')->insertAll($insert);
                }
        }
        echo PHP_EOL . "部分SPU的sku采购价不同-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    
    //部分SPU的sku采购价不同
    public function PartialSpuSkusHaveDifferentEdit(){
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $t1       = microtime(true);

        // $spus = ['sha226'];//十月
        // $spus = ['bra37'];//十月
        // $spus = ['bra111'];
        $spus = ['bra141'];
        //普通款22，印花款25
        foreach ($spus as $v) {
            $spucost = Db::name('ordercheck_skucost')
                ->field('id,spu,sku,material')
                ->where('date',"=",$date)
                ->where('spu',$v)
                ->select()->toarray();
                // halt($spucost);
                foreach ($spucost as $ks=>$vs) {
                    // $material = $this->DisassembleAttributes2($vs['sku']);
                    // $material = $this->DisassembleAttributesbra37($vs['sku']);
                    // $material = $this->DisassembleAttributesbra111($vs['sku']);
                    $material = $this->DisassembleAttributesbra141($vs['sku']);
                    $update = [
                        'sku' => $vs['sku'],
                        'material_total' => $material,
                    ];
                    DB::name('ordercheck_skucost')->where('id',$vs['id'])->update($update);
                    echo PHP_EOL . "已执行:" . $ks . '条' . PHP_EOL;
                }
        }
        echo PHP_EOL . "部分SPU的sku采购价不同-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
    * 拆分spu的属性
    * @param array params
    */
    public function DisassembleAttributes2($sku)
    {
        $material = 0;
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    foreach ($skuPlus as $v) {
                        if($v == "camellia " || $v == "camellia" || $v == "cherry beige"){
                            $material += 25;
                        }else{
                            $material += 22;
                        }
                    }
                }else{
                    if($sku[1] == "camellia " || $sku[1] == "camellia" || $sku[1] == "cherry beige"){
                        $material += 25;
                    }else{
                        $material += 22;
                    }
                }
                $count = $sku[3] ?? 1;
                $material = number_format((float)$material * (int)$count,2);
            }
        }
        return $material;
    }
    /**
    * 拆分spu的属性
    * @param array params
    */
    public function DisassembleAttributesbra37($sku)
    {
        $material = 0;
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    foreach ($skuPlus as $v) {
                        if($sku[2] == "3XL " || $sku[2] == "4XL"){
                            $material += 12;
                        }else{
                            $material += 11.5;
                        }
                    }
                }else{
                    if($sku[2] == "3XL " || $sku[2] == "4XL"){
                        $material += 12;
                    }else{
                        $material += 11.5;
                    }
                }
                $count = $sku[3] ?? 1;
                $material = number_format((float)$material * (int)$count,2);
            }
        }
        return $material;
    }

    
    /**
    * 拆分spu的属性
    * @param array params
    */
    public function DisassembleAttributesbra111($sku)
    {
        $material = 0;
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    foreach ($skuPlus as $v) {
                        if($sku[2] == "C"){
                            $material += 10.4;
                        }elseif($sku[2] == "D"){
                            $material += 10.9;
                        }elseif($sku[2] == "E"){
                            $material += 12.4;
                        }elseif($sku[2] == "F"){
                            $material += 14.4;
                        }elseif($sku[2] == "G"){
                            $material += 16.7;
                        }elseif($sku[2] == "H"){
                            $material += 19.2;
                        }else{
                            $material += 8;
                        }
                    }
                }else{
                    if($sku[2] == "C"){
                        $material += 10.4;
                    }elseif($sku[2] == "D"){
                        $material += 10.9;
                    }elseif($sku[2] == "E"){
                        $material += 12.4;
                    }elseif($sku[2] == "F"){
                        $material += 14.4;
                    }elseif($sku[2] == "G"){
                        $material += 16.7;
                    }elseif($sku[2] == "H"){
                        $material += 19.2;
                    }else{
                        $material += 8;
                    }
                }
                $count = $sku[3] ?? 1;
                $material = number_format((float)$material * (int)$count,2);
            }
        }
        $material = number_format((float)$material + 9.5,3);
        return $material;
    }


    
    
    /**
    * 拆分spu的属性
    * @param array params
    */
    public function DisassembleAttributesbra141($sku)
    {
        $material = 0;
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    foreach ($skuPlus as $v) {
                        if($sku[2] == "B"){
                            $material += 7.8;
                        }elseif($sku[2] == "C"){
                            $material += 7.8;
                        }elseif($sku[2] == "D"){
                            $material += 8.4;
                        }elseif($sku[2] == "E"){
                            $material += 9.4;
                        }elseif($sku[2] == "F"){
                            $material += 10.9;
                        }elseif($sku[2] == "G"){
                            $material += 12.9;
                        }else{
                            $material += 9.400;
                        }
                    }
                }else{
                    if($sku[2] == "B"){
                        $material += 7.8;
                    }elseif($sku[2] == "C"){
                        $material += 7.8;
                    }elseif($sku[2] == "D"){
                        $material += 8.4;
                    }elseif($sku[2] == "E"){
                        $material += 9.4;
                    }elseif($sku[2] == "F"){
                        $material += 10.9;
                    }elseif($sku[2] == "G"){
                        $material += 12.9;
                    }else{
                        $material += 9.400;
                    }
                }
                $count = $sku[3] ?? 1;
                $material = number_format((float)$material * (int)$count,2);
            }
        }
        return $material;
    }


    /**
    * 拆分spu的属性
    * @param array params
    */
    public function DisassembleAttributes($sku,$skus = [])
    {
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    foreach ($skuPlus as $v) {
                        $skus[$v] = 1;
                    }
                }else{
                    $skus[$sku[1]] = 1;
                }
            }
        }
        return $skus;
    }

    /**
    * 拆分spu的属性
    * @param array params
    */
    public function CheckTheNumberOfSkus()
    {
        $count = Db::name('checkbill_888')
            ->where('sku_info',"")
            ->count();
        // halt($count);
            
        $pageSize = 2000; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('checkbill_888')
                ->where('sku_info',"")
                ->limit($pageSize)
                ->order('id asc')
                ->select()
                ->toArray();
            foreach ($list as $k=>$v) {
                $update = [];
                $update['sku_info'] = "未知";
                $order_skuinfo = DB::name('order_skuinfo')
                    ->field('new_sku, SUM(realcount) as total_realcount')
                    ->where('order_id', $v['order_id'])
                    ->group('new_sku')
                    ->select()
                    ->toArray();
                $new_sku_strings = [];
                if(!empty($order_skuinfo)){
                    foreach ($order_skuinfo as $item) {
                        if($item['total_realcount'] > 1){
                            $new_sku_strings[] = $item['new_sku'] . '-' . $item['total_realcount'];
                        }else{
                            $new_sku_strings[] = $item['new_sku'];
                        }
                    }
                    $new_sku = implode(',', $new_sku_strings);
                    $update['sku_info'] = $new_sku ? $new_sku : "未知";
                }
                // halt($update);
                DB::name('checkbill_888')->where('id',$v['id'])->update($update);
                $executedCount++;
                echo PHP_EOL . "已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
            }
        }
        
    }

    //检查skuquantity
    public function ModifySkuQuantity(){
        $t1       = microtime(true);
        
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $where[]  = ['b.createtime', '>=', $start_time];
        $where[]  = ['b.createtime', '<=', $end_time];
        // $where[]  = ['b.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        // halt($where);
        
        $order_info = Db::name('order_info')
            ->field('
                SUM(count_total) as count_total,b.skuquantity,a.order_id
            ')
            ->alias('a')
            ->join('order_achievement b','b.order_id = a.order_id', 'left')
            ->where($where)
            ->group('a.order_id')
            ->select()
            ->toarray();
        $executedCount = 0;
        foreach ($order_info as $k=>$v) {
            if((int)$v['count_total'] !== (int)$v['skuquantity']){
                halt($v);
            }
            $executedCount++;
            echo PHP_EOL . "已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    //检查skuquantity
    public function order_historical3_woob(){
        $t1       = microtime(true);
        
        $count = Db::name('order_historical_woob')->where('order_id',null)->count();

        $order_historical = Db::name('order_historical_woob')
        ->where('order_id',null)->select()->toarray();
        $executedCount = 0;
        foreach ($order_historical as $k=>$v) {
            $order = Db::name('order')
                ->field('a.order_id')
                ->alias('a')
                ->where('a.name',$v['name'])
                ->where('a.shop_id',21)
                ->find();
            $update = [
                'order_id' => $order['order_id'],
            ];
            db::name('order_historical_woob')->where('id',$v['id'])->update($update);
            
            $executedCount++;
            echo PHP_EOL . "总共".$count."条，已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    //检查skuquantity
    public function order_historical2_woob(){
        $t1       = microtime(true);
        
        $count = Db::name('order_historical_woob')->where('type',2)->where('status',0)->count();

        $order_historical = Db::name('order_historical_woob')
        ->where('type',2)->where('status',0)->select()->toarray();
        $executedCount = 0;
        foreach ($order_historical as $k=>$v) {
            $order = Db::name('order')
                ->field('b.disputeapi_status')
                ->alias('a')
                ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
                ->where('a.name',$v['name'])
                ->where('a.shop_id',21)
                ->find();
            $disputeapi_status = $order['disputeapi_status'] ?? "";
            if($disputeapi_status == "暂无争议" || $disputeapi_status == "争议赢"){
                $update = [
                    'status' => 1,
                    'msg' => $disputeapi_status,
                ];
                db::name('order_historical_woob')->where('id',$v['id'])->update($update);
            }else{
                $update = [
                    'status' => 2,
                    'msg' => $disputeapi_status,
                ];
                db::name('order_historical_woob')->where('id',$v['id'])->update($update);
            }
            $executedCount++;
            echo PHP_EOL . "总共".$count."条，已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }
    //检查skuquantity
    public function order_historical_woob(){
        $t1       = microtime(true);
        
        $count = Db::name('order_historical_woob')->where('type',1)->where('status',0)->count();

        $order_historical = Db::name('order_historical_woob')
        ->where('type',1)->where('status',0)->select()->toarray();
        $executedCount = 0;
        foreach ($order_historical as $k=>$v) {
            $order = db::name('order')
                ->field('fulfillment_status')
                ->where('name',$v['name'])
                ->where('shop_id',21)
                ->find();
            $fulfillment_status = $order['fulfillment_status'] ?? "";
            if($fulfillment_status == "fulfilled"){
                $update = [
                    'status' => 1,
                    'msg' => "已发货",
                ];
                db::name('order_historical_woob')->where('id',$v['id'])->update($update);
            }else{
                $update = [
                    'status' => 2,
                    'msg' => "未发货",
                ];
                db::name('order_historical_woob')->where('id',$v['id'])->update($update);
            }
            $executedCount++;
            echo PHP_EOL . "总共".$count."条，已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    
    //检查skuquantity
    public function order_historical_test(){
        $t1       = microtime(true);
        
        $count = Db::name('order_historical_test')->where('order_id',null)->count();

        $order_historical = Db::name('order_historical_test')
        ->where('order_id',null)->select()->toarray();
        $executedCount = 0;
        foreach ($order_historical as $k=>$v) {
            $order = Db::name('order')
                ->field('a.order_id')
                ->alias('a')
                ->where('a.name',$v['name'])
                ->where('a.shop_id',17)
                ->find();
            $update = [
                'order_id' => $order['order_id'],
            ];
            db::name('order_historical_test')->where('id',$v['id'])->update($update);
            
            $executedCount++;
            echo PHP_EOL . "总共".$count."条，已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    //检查skuquantity
    public function order_historical_test2(){
        $t1       = microtime(true);
        
        $count = Db::name('order_historical_test2')->where('order_id',null)->count();

        $order_historical = Db::name('order_historical_test2')
        ->where('order_id',null)->select()->toarray();
        $executedCount = 0;
        foreach ($order_historical as $k=>$v) {
            $order = Db::name('order_historical_test')
                ->alias('a')
                ->where('a.name',$v['name'])
                ->find();
            $update = [
                'status' => $order['status'],
                'msg' => $order['msg'],
                'type' => $order['type'],
                'date' => $order['date'],
                'order_id' => $order['order_id'],
            ];
            db::name('order_historical_test2')->where('id',$v['id'])->update($update);
            
            $executedCount++;
            echo PHP_EOL . "总共".$count."条，已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }
    

    //检查skuquantity
    public function order_historical3(){
        $t1       = microtime(true);
        
        $count = Db::name('order_historical')->where('order_id',null)->count();

        $order_historical = Db::name('order_historical')
        ->where('order_id',null)->select()->toarray();
        $executedCount = 0;
        foreach ($order_historical as $k=>$v) {
            $order = Db::name('order')
                ->field('a.order_id')
                ->alias('a')
                ->where('a.name',$v['name'])
                ->where('a.shop_id',17)
                ->find();
            $update = [
                'order_id' => $order['order_id'],
            ];
            db::name('order_historical')->where('id',$v['id'])->update($update);
            
            $executedCount++;
            echo PHP_EOL . "总共".$count."条，已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    //检查skuquantity
    public function order_historical2(){
        $t1       = microtime(true);
        
        $count = Db::name('order_historical')->where('type',2)->where('status',0)->count();

        $order_historical = Db::name('order_historical')
        ->where('type',2)->where('status',0)->select()->toarray();
        $executedCount = 0;
        foreach ($order_historical as $k=>$v) {
            $order = Db::name('order')
                ->field('b.disputeapi_status')
                ->alias('a')
                ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
                ->where('a.name',$v['name'])
                ->where('a.shop_id',17)
                ->find();
            $disputeapi_status = $order['disputeapi_status'] ?? "";
            if($disputeapi_status == "暂无争议" || $disputeapi_status == "争议赢"){
                $update = [
                    'status' => 1,
                    'msg' => $disputeapi_status,
                ];
                db::name('order_historical')->where('id',$v['id'])->update($update);
            }else{
                $update = [
                    'status' => 2,
                    'msg' => $disputeapi_status,
                ];
                db::name('order_historical')->where('id',$v['id'])->update($update);
            }
            $executedCount++;
            echo PHP_EOL . "总共".$count."条，已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }
    //检查skuquantity
    public function order_historical(){
        $t1       = microtime(true);
        
        $count = Db::name('order_historical')->where('type',1)->where('status',0)->count();

        $order_historical = Db::name('order_historical')
        ->where('type',1)->where('status',0)->select()->toarray();
        $executedCount = 0;
        foreach ($order_historical as $k=>$v) {
            $order = db::name('order')
                ->field('fulfillment_status')
                ->where('name',$v['name'])
                ->where('shop_id',17)
                ->find();
            $fulfillment_status = $order['fulfillment_status'] ?? "";
            if($fulfillment_status == "fulfilled"){
                $update = [
                    'status' => 1,
                    'msg' => "已发货",
                ];
                db::name('order_historical')->where('id',$v['id'])->update($update);
            }else{
                $update = [
                    'status' => 2,
                    'msg' => "未发货",
                ];
                db::name('order_historical')->where('id',$v['id'])->update($update);
            }
            $executedCount++;
            echo PHP_EOL . "总共".$count."条，已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    //同步订单状态
    public function SynchronizeOrderTime(){
        $t1       = microtime(true);

        $sql = "
            SELECT o.order_id,
            o.shop_id,o.createtime,a.createtime as createtime2
            FROM qu_order o  
            LEFT JOIN qu_order_achievement a ON o.order_id = a.order_id 
            WHERE 
            o.createtime != a.createtime 
            ORDER BY o.order_id DESC 
            LIMIT 1000;
        ";
        $order_info = Db::query($sql);
        halt($order_info);
        // FROM qu_order o  
        // FROM qu_order_source o  
        $sql = "
            SELECT o.order_id,
            o.shop_id,o.createtime,a.createtime as createtime2,
            o.created_at,a.created_at as created_at2
            FROM qu_order_source o  
            LEFT JOIN qu_order a ON o.order_id = a.order_id 
            WHERE 
            o.created_at != a.created_at 
            ORDER BY o.order_id DESC 
            LIMIT 1000;
        ";
        $order_info = Db::query($sql);
        halt($order_info);
        $executedCount = 0;
        $executedCountsu = 0;
        foreach ($order_info as $k=>$v) {
            if($v['created_at'] !== $v['created_at2']){
            // if((int)$v['createtime'] !== (int)$v['createtime2']){
                halt($v);
                
                $update = [];
                // $update['createtime'] = $v['createtime2'];
                $update['created_at'] = $v['created_at'];
                Db::name('order')->where('order_id',$v['order_id'])->update($update);
                // Db::name('order_source')->where('order_id',$v['order_id'])->update($update);
                $executedCountsu++;
            }
            $executedCount++;
            echo PHP_EOL . "成功".$executedCountsu.",已执行:" . $executedCount . '-----' . '当前' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }
    //采购
    public function EstimatedCostPerOrderPurchase(){
        $t1       = microtime(true);

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time];

        // $where[]  = ['shop_id', '=', 5];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        //清空1
        // $count = Db::name('order_achievement')
        //     ->alias('a')
        //     ->join('qu_order_info b','b.order_id = a.order_id', 'left')
        //     ->where($where)
        //     ->where('b.count',0)
        //     ->where('a.material',"<",0.001)
        //     ->count();
        //     halt($count);
        $update = [];
        $update['a.material'] = 0;
        $update['a.material_status'] = "";
        $update = Db::name('order_achievement')
            ->alias('a')
            ->join('qu_order_info b','b.order_id = a.order_id', 'left')
            ->where($where)
            ->where('b.count',0)
            ->where('a.material',"<",0.001)
            ->update($update);
            // halt($update);
            
        //清空2 
        // $update = [];
        // $update['material'] = 0;
        // $update['material_status'] = "";
        // $update = Db::name('order_achievement')
        //     ->where($where)
        //     ->update($update);
        //     halt($update);
        //清空

        $count = Db::name('order_achievement')
            // ->where('order_id',"=","5974428024893")
            ->where('material',"<",0.001)
            ->where($where)
            ->count();
        // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('order_id,createtime')
                // ->where('order_id',"=","5974428024893")
                // ->where('material_status',"=","")
                ->where('material',"<",0.001)
                ->where($where)
                ->limit($pageSize)
                ->order('id desc')
                ->select()
                ->toArray();
                // halt($list);
                
            foreach ($list as $v){
                // halt($v);
                
                //预估采购成本
                $this->add_material($v,$start_time);
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "预估每单采购成本-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    /**
     *更新订单采购
     */
    public function add_material($order,$timedate)
    {
        $order_quantity = table('order_info')
            ->field('id,spu,sku,quantity,order_id')
            ->where('order_id', $order['order_id'])
            ->select()
            ->toarray();
        // halt($order['order_id']);

        //临时检查
        // if(!empty($order_quantity)){
        //     foreach ($order_quantity as $item) {
        //         echo "暂无采购成本的SPU：".$item['spu'].',sku:'.$item['sku'];
        //     }
        // }else{
        //     echo $order['order_id'];
        // }
        //临时检查
        
        $material = 0;
        //新方法
        if (!empty($order_quantity)) {
            foreach ($order_quantity as $item) {
                if (empty($item['sku'])) {
                    $material += 0.001;
                    continue;
                }
                $skucost = table('ordercheck_skucost')
                    ->where('sku', $item['sku'])
                    ->where('timedate', $timedate)
                    ->find(); 
                    
                if(empty($skucost)){
                    $skucost = Db::name('ordercheck_skucost')
                        ->where('sku', $item['sku'])
                        ->where('material_total',">",0)
                        ->order('timedate desc')
                        ->find(); 
                }
                if(empty($skucost)){
                    $spucost = Db::name('ordercheck_spucost')
                        ->where('spu', $item['spu'])
                        ->where('material',">",0)
                        ->order('timedate desc')
                        ->find(); 
                    if(empty($spucost)){
                        $product = Db::name('product')
                            ->where('spu',$item['spu'])
                            ->order('purchase_cost desc')
                            ->find();
                        if(isset($product) && $product['purchase_cost'] > 0.01){
                            $spucost['material'] = $product['purchase_cost'];
                            $spucost['timedate'] = $timedate;
                            $spucost['date'] = date('Y-m', $timedate);
                        }else{
                            //包含
                            if(strpos($item['sku'],'giftcard') !== false){
                                $spucost['material'] = 0.001;
                                $spucost['timedate'] = $timedate;
                                $spucost['date'] = date('Y-m', $timedate);
                            }else{
                                $msg = "SPU:".$item['spu']."暂无采购成本,SKU:".$item['sku']."请尽快添加";
                                echo $msg;
                                continue;
                            }
                        }
                    }
                    $arr_sku['material'] = $spucost['material'];
                    $arr_sku['spu'] = $item['spu'];
                    $arr_sku['sku'] = $item['sku'];
                    $arr_sku['date'] = $spucost['date'];
                    $arr_sku['timedate'] = $spucost['timedate'];
                    $count = (new ApiOrdercheckLogic())->CountTheNumberOfItems($item);
                    $arr_sku['count'] = $count;
                    $arr_sku['material_total'] = (float)number_format((float)$spucost['material'] * $count, 3, '.', '');
                    Db::name('ordercheck_skucost')->insert($arr_sku);
                    $skucost = $arr_sku;
                }
                // halt($skucost);
                $skucost['material'] = $skucost['material']??0;
                $skucost['count'] = $skucost['count']??0;
                $skucost['material_total'] = $skucost['material_total']??0;
                if (!empty($skucost) && $item['quantity'] >= 1) {
                    $newmaterial = (float)number_format((float)$skucost['material_total']*(int)$item['quantity'], 3, '.', '');
                    $material = (float)number_format((float)$material + $newmaterial, 3, '.', '');
                }
                //info表新增采购成本明细
                $update_orderinfo = [
                    'count'   => $skucost['count'],
                    'material'  => $skucost['material'],
                    'count_total'   => (int)number_format((float)$skucost['count']*(int)$item['quantity'], 3, '.', ''),
                    'material_total'  => (float)number_format((float)$skucost['material_total']*(int)$item['quantity'], 3, '.', ''),
                ];
                // halt($update_orderinfo);
                
                Db::name('order_info')->where('id',$item['id'])->update($update_orderinfo);
            }
        }
        // halt($material);
        $data['material'] = $material;
        $data['material_status'] = "匹配成功";
        //估算开始
        if (empty($material)) {
            $data['material'] = 0;
            $data['material_status'] = "未找到成本";
        }
        // halt($data);
        
        Db::name('order_achievement')->where('order_id', $order['order_id'])->update($data);
        return true;
    }

    /**
     *更新订单物流
     */
    public function add_freight($order,$dollar)
    {
        if($order['freight'] > 0){
            return true;
        }
        // $order_count = Db::name('order_fulfillments')
        //     ->where('order_id',$order['order_id'])
        //     ->count();
        $order_fulfillments = Db::name('order_fulfillments')
            ->where('order_id',$order['order_id'])
            ->select()->toarray();
        $SplitTheOrderAsEmpty = 0;
        if(!empty($order_fulfillments)){
            $ordertransfer['freight'] = 0;
            $ordertransfer['weight'] = 0;
            foreach ($order_fulfillments as $k=>$v) {
                if (!empty($v['tracking_number'])) {
                    $ordertransfer_l = Db::name('ordercheck_logistics')
                        ->field('freight,weight')
                        ->where('transfer_number', $v['tracking_number'])
                        ->order('freight desc')
                        ->find();
                    //方法2---历史数据
                    if(empty($ordertransfer_l)){
                        //转单号
                        $number = $v['tracking_number'];
                        $result = $this->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$number);
                        $resultData = json_decode($result['result'], true);
                        $v['tracking_number'] = $resultData[0]['data'][0]['business_channeltransfercode'] ?? "";
                        if (!empty($v['tracking_number'])) {
                            // halt($v['tracking_number']);
                            $ordertransfer_l = Db::name('ordercheck_logistics')
                                ->field('freight,weight')
                                ->where('transfer_number', $v['tracking_number'])
                                ->order('freight desc')
                                ->find();
                        }
                    }
                    if(!empty($ordertransfer_l)){
                        if($ordertransfer_l['freight'] == 0){
                            $ordertransfer_l['freight'] = 0.001;
                        }
                        $ordertransfer['freight'] = (float)number_format((float)$ordertransfer['freight'] + $ordertransfer_l['freight'], 3, '.', '');
                        $ordertransfer['weight'] = (float)number_format((float)$ordertransfer['weight'] + $ordertransfer_l['weight'], 3, '.', '');
                    }else{
                        $SplitTheOrderAsEmpty = 1;
                        break;
                    }
                }else{
                    $SplitTheOrderAsEmpty = 1;
                    break;
                }
            }
        }else{
            $ordertransfer = array();
            if (!empty($order['tracking_number'])) {
                //方法2---物流费总和
                // $ordertransfer = Db::name('ordercheck_logistics')
                //     ->field('SUM(freight) as freight')
                //     ->where('transfer_number', $order['tracking_number'])
                //     ->find();
                $ordertransfer = Db::name('ordercheck_logistics')
                    ->field('freight,weight')
                    ->where('transfer_number', $order['tracking_number'])
                    ->order('freight desc')
                    ->find();
                    
                //方法2---历史数据
                // if(empty($ordertransfer)){
                //     $ordertransfer = Db::name('ordercheck_logistics_copy')
                //     ->field('freight,weight')
                //     ->where('transfer_number', $order['tracking_number'])
                //     ->order('freight desc')
                //     ->find();
                // }
            }
        }
        //拆单
        if($SplitTheOrderAsEmpty == 1){
            $ordertransfer['freight'] = 0;
            $ordertransfer['weight'] = 0;
        }

        // halt($ordertransfer);
        //估算开始
        
            // halt($order);
            // try {
            //     $info = (new FreightLogic())->get_estimate_fee($order['order_id']);
            // } catch (ValidateException $e) {
            //     $info['weight'] = 0;
            //     $info['fee'] = 0;
            // } catch (\Exception $e) {
            //     $info['weight'] = 0;
            //     $info['fee'] = 0;
            // }
            $data['estimate_weight'] = 0;
            $data['estimate_freight'] = 0;
            $data['freight'] = 0;
            $data['freight_status'] = "未找到成本";
            // halt($data);
            
            // if($data['estimate_weight'] > 0){
            //     $data['freight'] = 0;
            //     $data['freight_status'] = "预估物流费";
            //     //拆单
            //     if($SplitTheOrderAsEmpty == 1){
            //         $estimate_freight = $data['estimate_freight'] ?? 0;
            //         $total_price = $order['total_price'] ?? 0;
            //         if($estimate_freight > 0 && $total_price > 0){
            //             //检查比例
            //             $InspectionRatio = number_format($estimate_freight/$dollar/$total_price*100, 3, '.', '');
            //             if($InspectionRatio < 5){
            //                 //异常
            //                 $data['estimate_freight'] = number_format($total_price*0.12*$dollar, 3, '.', '');//人民币
            //             }
            //         }
            //         if($order_count > 1){
            //             $data['freight_status'] = "物流账单信息不全(拆单)";
            //         }else{
            //             $data['freight_status'] = "物流账单信息不全";
            //         }
            //     }
            // }else{
            //     $data['freight'] = 0;
            //     $data['freight_status'] = "未找到成本";
            // }
        
        if (isset($ordertransfer['freight']) && $ordertransfer['freight'] !== 0) {
            if ($ordertransfer['freight'] < 0) {  
                $ordertransfer['freight'] = 0;  
            }
            $data['freight'] = $ordertransfer['freight'];
            $data['estimate_freight'] = $ordertransfer['freight'];
            $data['freight_weight'] = $ordertransfer['weight'] ?? 0;
            $data['freight_status'] = "匹配成功";
            // halt($data);
            //异常
            $freight_Abnormal = $data['freight'] ?? 0;
            $total_price = $order['old_total_price'] ?? 0;
            //partially_refunded
            // halt($order);
            if($order['financial_status'] == "partially_refunded"){
                $data['freight'] = number_format($total_price*0.12*$dollar, 3, '.', '');
                $data['freight_status'] = "部分退款--预估值(销售额*12%)";
            }else if($freight_Abnormal > 0 && $total_price > 0){
                //检查比例
                $InspectionRatio = number_format($freight_Abnormal/$dollar/$total_price*100, 3, '.', '');
                if($InspectionRatio < 5){
                    //异常
                    $data['freight'] = number_format($total_price*0.12*$dollar, 3, '.', '');//人民币
                    $data['freight_status'] = "比例异常--预估值(销售额*12%)";
                }
            }
        }else{
            $total_price = $order['old_total_price'] ?? 0;
            $data['freight'] = number_format($total_price*0.12*$dollar, 3, '.', '');//人民币
            $data['estimate_freight'] = number_format($total_price*0.12*$dollar, 3, '.', '');//人民币
            $data['freight_status'] = "未找到成本--预估值(销售额*12%)";
        }
        // halt($data);
        Db::name('order_achievement')->where('order_id', $order['order_id'])->update($data);
        return true;
    }

    /**
    * @desc    争议成本
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function add_dispute($v)
    {
        $dispute['status'] = 2;

        $order = Db::name('order')->where('tracking_number', $v['transfer_number'])->find();
        if (!empty($order)) {
            $dispute['status'] = 1;
            $data['dispute'] = $v['cost'];
            Db::name('order_achievement')->where('order_id', $order['order_id'])->update($data);
            return $dispute;
        } 
        
        $order = Db::name('order_customer')->where('email', $v['transfer_number'])->find();
        if (!empty($order)) {
            $dispute['status'] = 1;
            $data['dispute'] = $v['cost'];
            Db::name('order_achievement')->where('order_id', $order['order_id'])->update($data);
            return $dispute;
        }

        $order = Db::name('order_transactions')->where('payment_id', $v['transfer_number'])->find();
        if (!empty($order)) {
            $dispute['status'] = 1;
            $data['dispute'] = $v['cost'];
            Db::name('order_achievement')->where('order_id', $order['order_id'])->update($data);
            return $dispute;
        }
        
        return $dispute;
    }
    

     //spu为空
    public function AddOrderSearchField(){
        $t1       = microtime(true);
        $count = Db::name('order_achievement')
            ->where('spu',"=","")
            ->order('id desc')
            ->count();
            // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('order_id')
                ->where('spu',"=","")
                ->order('id desc')
                ->limit(500)
                ->select()
                ->toArray();
            foreach ($list as $v){
                $line_items = Db::name('order_info')
                    ->field('sku,spu')
                    ->where('order_id',$v['order_id'])
                    ->select()->toarray();
                $arr_source_skus = [];
                $arr_source_spus = [];
                if(!empty($line_items)){
                    foreach ($line_items as $line_item) {  
                        if(!empty($line_item['sku'])){
                            $arr_source_skus[] = $line_item['sku'];
                        }
                        if(!empty($line_item['spu'])){
                            $arr_source_spus[] = $line_item['spu'];
                        }
                    }
                    $arr_source_skus = array_unique($arr_source_skus);
                    if(!empty($arr_source_skus)){
                        $arr_source_skus = implode(',',$arr_source_skus);
                    }
                    $arr_source_spus = array_unique($arr_source_spus);
                    if(!empty($arr_source_spus)){
                        $arr_source_spus = implode(',',$arr_source_spus);
                    }
                    $update = [];    
                    $update['spu'] = $arr_source_spus ?? "";
                    $update['sku'] = $arr_source_skus ?? "";
                    $update['order_id'] = $v['order_id'] ?? 0;
                    // halt($update);
                    Db::name('order_achievement')->where('order_id',$update['order_id'])->update($update);
                    if(!empty($update['spu']) || !empty($update['sku'])){
                        $executedCountsu++;
                    }
                }
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.',当前第' .$i.'页' . PHP_EOL;
                
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    public function dateTimeStr($dateTimeStr) {  
        $posT = strpos($dateTimeStr, 'T');  
        if ($posT !== false) {  
            $datePart = substr($dateTimeStr, 0, $posT);  
            $timePart = substr($dateTimeStr, $posT + 1, strpos($dateTimeStr, '-', $posT + 1) - ($posT + 1));  
            $formattedDateTime = $datePart . ' ' . $timePart;  
            $formattedDateTime = strtotime($formattedDateTime);
            if (!$formattedDateTime) {  
                $datePart = substr($dateTimeStr, 0, $posT);  
                $timePart = substr($dateTimeStr, $posT + 1, strpos($dateTimeStr, '+', $posT + 1) - ($posT + 1));  
                $formattedDateTime = $datePart . ' ' . $timePart;  
                $formattedDateTime = strtotime($formattedDateTime);
                return $formattedDateTime;
            }else{
                return $formattedDateTime;
            }
        } else {  
            return 0;
        }  
    }

    //每月统计业绩--订单标记到个人
    public function MonthlyPerformanceStatistics(){
        //标签
        // $get_channel_rate = (new OrderSourceLogic())->arr_campaign();
        $get_channel_rate = (new OrderSourceWoobillyLogic())->arr_campaign();
        foreach ($get_channel_rate as $k=>$v) {
            db::name('system_admin')->where('username',$v['label'])->update(['tag_campaign'=>$v['value']]);
            echo "修改".$v['label'].'标签--'.$v['value'].PHP_EOL;
        }
        
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $where = [];
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        //二次检查
        // $where[]  = ['shop_id', 'in', [17]];
        $where[]  = ['shop_id', 'in', [18]];
        // $where[]  = ['shop_id', 'not in', [17, 5]];

        //纠错
        $count = Db::name('order_achievement')
            ->where($where)
            ->where('admin_id',"-1")
            ->count();
        if($count > 0){
            echo "纠错".$count."条".PHP_EOL;
            $update1['source'] = "";
            $update1['admin_id'] = "";
            Db::name('order_achievement')
                ->where($where)
                ->where('admin_id',"-1")
                ->update($update1);
        }

        //搜素方式1---匹配直流
        // $where[]  = ['source', '<', "1"];
        //搜素方式2----匹配个人业绩
        $where[]  = ['admin_id', '<', "1"];

        // $where[]  = ['id', '=', 80805];
        // halt($where);
        
        // $update1['source'] = "";
        // $update1['admin_id'] = "";
        // $updates = Db::name('order_achievement')
        //     ->where($where)
        //     ->update($update1);
        // halt($updates);
            
        
        // $where[]  = ['admin_id', '=', "85"];
        $t1       = microtime(true);
        $count = Db::name('order_achievement')
            // ->field('SUM(dispute) as dispute')
            ->where($where)
            // ->select();
            ->count();
        // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('shop_id,order_id,createtime')
                ->where($where)
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                
                $this->LargeStore($v);//大店铺匹配方式
                // $this->SmallShop($v);//小店铺匹配方式
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
                
            }
        }
        echo PHP_EOL . "大店铺订单标记到个人-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
    * @desc    大店铺匹配方式
    * @date    2024/9/20
    * @author  zhangheng
    */
    public function LargeStore($order)
    {
        $order_source = Db::name('order_source')
            ->field('a.order_id,a.tag_campaign,b.id,a.tag_source')
            ->alias('a')
            ->join('qu_system_admin b','b.tag_campaign = a.tag_campaign', 'left')
            ->where('a.order_id',$order['order_id'])
            ->find();
            
        if($order_source){
            $update['admin_id'] = $order_source['id'] ?? "-1";
            $update['source'] = $order_source['tag_source'] ?? "";

            //吴靓丽判断email
            if($order_source['tag_source'] == 'email'){
                $order_source = Db::name('order_source')
                ->field('a.order_id,a.tag_campaign,b.id,a.tag_source')
                ->alias('a')
                ->join('qu_system_admin b','b.tag_campaign = a.tag_source', 'left')
                ->where('a.order_id',$order['order_id'])
                ->find();
                $update['admin_id'] = $order_source['id'] ?? "-1";
                $update['source'] = $order_source['tag_source'];
            }
            //TODO特殊判断--impact给孙义翔
            if($order_source['tag_source'] == 'impact'){
                // $update['admin_id'] = 85;
                // $update['source'] = 'impact';
            }
        }else{    
            $update['admin_id'] = $order_source['id'] ?? "-1";
        }
        // halt($update);
        // if($update['admin_id'] <= 0 && $update['source'] != "impact"){
            // halt($order);
        // }
        // halt($update);
        Db::name('order_achievement')->where('order_id',$order['order_id'])->update($update);
        return true;
    }
    
    //每月统计店铺业绩
    public function MonthlyStatisticsOfStore(){
        $shops = Db::name('shops')
            ->field('id,name')
            ->where('type','shopify')
            ->select()
            ->toarray();
        foreach ($shops as $k=>$v) {
            $this->MonthlyStatisticsOfStore_admin($v);
            echo PHP_EOL . "" . $v['name'] . '完成,'.$k.'' . PHP_EOL;
        }
    }
    //每月统计店铺业绩
    public function MonthlyStatisticsOfStore_admin($shop){
        $shop_id = $shop['id'];
        $shop_name = $shop['name'];
        $t1       = microtime(true);

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $where = [];
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        $where[]  = ['shop_id', '=', $shop_id];

        $dispute_array = Db::name('order_achievement')
            ->field('
            COUNT(id) as count,
            sum(total_price) as total_price_old,
            sum(dispute) as dispute
            ')
            ->where($where)
            ->select()
            ->toarray();
        $dispute = $dispute_array[0]['dispute'] ?? 0;
        $total_price_old = $dispute_array[0]['total_price_old'] ?? 0;
        $count_old = $dispute_array[0]['count'] ?? 0;

        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];   

        //物流
        $where2  = [];
        $where2[]  = ['freight', '>', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(freight) as freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $freight = $freight_array[0]['freight'] ?? 0;

        $where2  = [];
        $where2[]  = ['freight', '<=', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(estimate_freight) as estimate_freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $estimate_freight = $freight_array[0]['estimate_freight'] ?? 0;

        $Achievement = Db::name('order_achievement')
            ->field('
            COUNT(id) as count_LogisticsMarkupFee,
            sum(material) as material
            ')
            ->where($where)
            ->select()
            ->toarray();

        $Achievements = $Achievement[0] ?? [];

        if(empty($Achievements)){
            return true;
        }

        $timedate = strtotime($date);
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();

        //计算销售额加两个条件
        $where[]  = ['disputeapi_status', 'in', ["争议赢", "暂无争议"]];

        $total_price = Db::name('order_achievement')
            ->field('
            sum(total_price) as total_price,
            sum(skuquantity) as skuquantity
            ')
            ->where($where)
            ->select()
            ->toarray();
        $Achievements['total_price'] = $total_price[0]['total_price'] ?? 0;
        $Achievements['skuquantity'] = $total_price[0]['skuquantity'] ?? 0;

        $Achievements['total_price_old'] = $total_price_old;
        $Achievements['count'] = $count_old;

        $Achievements['dispute'] = $dispute;

        $Achievements['freight'] = number_format((float)$freight + (float)$estimate_freight, 3, '.', '');
        
        //物流--人民币转美金
        $Achievements['freight'] = (float)number_format((float)$Achievements['freight'] / $order_exchange['dollar'], 3, '.', '');
        //采购
        $Achievements['material'] = (float)number_format((float)$Achievements['material'] / $order_exchange['dollar'], 3, '.', '');
        //打包费
        $Achievements['LogisticsMarkupFee'] = (float)number_format((float)$Achievements['count_LogisticsMarkupFee'] * $order_exchange['LogisticsMarkupFee'], 3, '.', '');

        // halt($Achievements);
        //广告
        $Achievements['advertising'] = 0;

        //利润
        $Achievements['profit'] = 0;

        $Achievements['date'] = $date;
        $Achievements['timedate'] = $timedate;
        $Achievements['shop_id'] = $shop_id;
        $Achievements['shop_name'] = $shop_name;

        Db::name('report_monthly_profit')
            ->where('date',$date)
            ->where('shop_id',$shop_id)
            ->delete();
        Db::name('report_monthly_profit')->insert($Achievements);
        return true;
    }

    //小店铺订单标记到个人
    public function TagSmallStoreOrdersToIndividuals(){
        // list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        // $where = [];
        // $where[]  = ['createtime', '>=', $start_time];
        // $where[]  = ['createtime', '<=', $end_time]; 
        // $where[]  = ['shop_id', 'not in', [17, 5]];
        // $update1['source'] = "";
        // $update1['admin_id'] = "";
        // $updates = Db::name('order_achievement')
        //     ->where($where)
        //     ->update($update1);
        // halt($updates);

        $list = Db::name('system_admin')
            ->field('a.id,a.nickname,a.phone')
            ->alias('a')
            ->join('qu_system_group_admin b','b.admin_id = a.id', 'left')
            ->where('b.group_id',11)
            ->select()
            ->toarray();
        foreach ($list as $k=>$v) {
            $this->MonthlyStatistics_admin($v['id']);
            echo PHP_EOL . "" . $v['nickname'] . '完成' . PHP_EOL;
        }
    }
    //每月统计运营业绩
    public function MonthlyStatistics_admin($admin_id){
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        //测试----正式方法需要传参
        
        //相关运营归属记录
        $query_date = [
            'start_time'  => $start_time,
            'end_time' => $end_time,
            'admin_id' => $admin_id,
        ];
        $lists = $this->OperationOwnership($query_date);
        if(empty($lists)){
            return true;
        }        
        foreach ($lists as $k=>$v) {
            //重新整理时间段
            $v = $this->ReorganizeTimePeriods($v,$query_date);
            switch ($v['type']) {
                //单人店铺业绩
                case '1': 
                    $this->SinglePersonStorePerformance($v);
                    break;
                //多人店铺业绩
                case '2':
                    $this->MultiPersonStorePerformance($v);
                    break;
                default:
            }
        }
        return true;
    }
    
    //渠道内分配
    public function WithinTheChannel(){
        //渠道内分配跟渠道外分配
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        $sources = Db::name('report_monthly_personal')
            ->field('source')
            ->where('date',$date)
            ->group('source')
            ->select()->toarray();

        $query_date = [
            'start_time'  => $start_time,
            'end_time' => $end_time,
        ];
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();

        foreach ($sources as $k=>$v) {
            $Achievements = [];
            switch ($v['source']) {
                case 'fb':
                    $Achievements = $this->WithinTheChannelAchievements($v['source'],$query_date,$order_exchange);
                    break;
                case 'tt':
                    $Achievements = $this->WithinTheChannelAchievements($v['source'],$query_date,$order_exchange);
                    break;
                case 'ggad':
                    $Achievements = $this->WithinTheChannelAchievements($v['source'],$query_date,$order_exchange);
                    break;
                default:
                    $Achievements = [];
            }
            if(empty($Achievements)){
                continue;
            }
            //存表
            $Achievements['admin_name'] = $v['source']."渠道内分配";
            $Achievements['admin_id'] = 0;
            $Achievements['date'] = $date;
            $Achievements['timedate'] = $start_time;
            $Achievements['dollar'] = $order_exchange['dollar'] ?? 0;
            //94%销售额
            $Achievements['total_price_handle'] = (float)number_format((float)$Achievements['total_price'] * 0.94, 3, '.', '');

            Db::name('report_monthly_personal')
                ->where('date',$date)
                ->where('admin_name',$Achievements['admin_name'])
                ->delete();
            Db::name('report_monthly_personal')->insert($Achievements);
            echo PHP_EOL . "渠道内分配：" . $v['source'] . '完成,'.$k.'' . PHP_EOL;
        }
    }

    //渠道外分配
    public function DistributionOutsideTheChannel(){
        //渠道内分配跟渠道外分配
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $query_date = [
            'start_time'  => $start_time,
            'end_time' => $end_time,
        ];
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();

        $Achievements = $this->DistributionOutsideTheChannelAchievements($query_date,$order_exchange);
        //存表
        $Achievements['admin_name'] = "渠道外分配";
        $Achievements['admin_id'] = 0;
        $Achievements['date'] = $date;
        $Achievements['timedate'] = $start_time;
        $Achievements['dollar'] = $order_exchange['dollar'] ?? 0;
        //94%销售额
        $Achievements['total_price_handle'] = (float)number_format((float)$Achievements['total_price'] * 0.94, 3, '.', '');

        Db::name('report_monthly_personal')
            ->where('date',$date)
            ->where('admin_name',$Achievements['admin_name'])
            ->delete();
        Db::name('report_monthly_personal')->insert($Achievements);
        echo PHP_EOL . "渠道外分配" . $date . '完成,' . PHP_EOL;
    }

    //小店未分配
    public function SmallShopNotAllocated(){
        $where[]  = ['id', 'not in', [17, 5]];
        $shops = Db::name('shops')
            ->field('id,name')
            ->where('type','shopify')
            ->where($where)
            ->select()
            ->toarray();
// halt($shops);
        //渠道内分配跟渠道外分配
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $query_date = [
            'start_time'  => $start_time,
            'end_time' => $end_time,
        ];
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();
            
        foreach ($shops as $k=>$v) {
            $Achievements = $this->SmallShopNotAllocatedAchievements($v['id'],$query_date,$order_exchange);
            if(empty($Achievements['total_price'])){
                echo PHP_EOL . "" . $v['name'] . '暂无订单,'.$k.'' . PHP_EOL;
                continue;
            }
            // halt($Achievements);
            
            //存表
            $Achievements['admin_name'] = $v['name']."店铺业绩公司部分";
            $Achievements['admin_id'] = 0;
            $Achievements['date'] = $date;
            $Achievements['timedate'] = $start_time;
            $Achievements['dollar'] = $order_exchange['dollar'] ?? 0;
            //94%销售额
            $Achievements['total_price_handle'] = (float)number_format((float)$Achievements['total_price'] * 0.94, 3, '.', '');

            Db::name('report_monthly_personal')
                ->where('date',$date)
                ->where('admin_name',$Achievements['admin_name'])
                ->delete();
            Db::name('report_monthly_personal')->insert($Achievements);
            echo PHP_EOL . "" . $v['name'] . '完成,'.$k.'' . PHP_EOL;
        }
    }

    
    //每月统计运营业绩-只计算提成部分
    public function MonthlyStatisticsOfpersonalCommission(){
        //测试----正式方法需要传参
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();

        $list = Db::name('report_monthly_personal')
            ->where('date',$date)
            // ->where('admin_id',"<>",0)
            ->where('admin_id',85)
            ->select()
            ->toarray();
        foreach ($list as $k=>$v) {

            $v['commission'] = (float)number_format((float)$v['total_price_handle'] - $v['freight'] - $v['material'] - $v['LogisticsMarkupFee'] - $v['advertising'] - $v['dispute'] + $v['chananel_total'], 2, '.', '');
            
            $v['commission_old'] = $v['commission'];
            $v = $this->commission($v);
            //换算人民币
            $v['commission'] = (float)number_format((float)$v['commission'] * $order_exchange['dollar'], 3, '.', '');

            $update['commission_old'] = $v['commission_old'];
            $update['commission'] = $v['commission'];
// halt($update);

            Db::name('report_monthly_personal')
                ->where('date',$v['date'])
                ->where('admin_id',$v['admin_id'])
                ->update($update);
            
            echo PHP_EOL . "" . $v['admin_name'] . '完成,'.$k.'' . PHP_EOL;
        }
    }

    //每月统计运营业绩
    public function MonthlyStatisticsOfpersonal(){
        //删除85 孙义翔的标签
        
        $list = Db::name('system_admin')
            ->field('a.id,a.nickname,a.phone')
            ->alias('a')
            ->join('qu_system_group_admin b','b.admin_id = a.id', 'left')
            ->where('b.group_id',11)
            ->where('a.id',"<>",85)
            // ->where('a.id',"=",69)
            ->select()
            ->toarray();
            // halt($list);
        foreach ($list as $k=>$v) {
            $this->MonthlyStatisticsOfpersonal_admin($v['id'],$v['nickname']);
            echo PHP_EOL . "" . $v['nickname'] . '完成,'.$k.'' . PHP_EOL;
        }
    }

    //每月统计运营业绩
    public function MonthlyStatisticsOfpersonal_admin($admin_id,$nickname){
        //测试----正式方法需要传参
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        //相关运营归属记录
        $query_date = [
            'start_time'  => $start_time,
            'end_time' => $end_time,
            'admin_id' => $admin_id,
        ];
// halt($query_date);
        //查找未归属订单
        // $where[]  = ['createtime', '>=', $query_date['start_time']];
        // $where[]  = ['createtime', '<=', $query_date['end_time']];
        // // $where[]  = ['admin_id', '=', 0];
        // $where[]  = ['admin_id', '=', "-1"];
        // $update_admin['admin_id'] = "-1";
        // $Achievement = Db::name('order_achievement')
        //     ->where($where) 
        //     ->whereNotIn('shop_id', [17, 5])
        //     ->limit(10)
        //     ->select()
        //     ->toarray();
        //     // ->update($update_admin);
        // halt($Achievement);
        
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();
            
        //小店铺
        $AchievementsSmall = $this->SmallShopProfit($query_date,$order_exchange);
        // halt($AchievementsSmall);
        
        //大店铺
        $AchievementsLarge = $this->LargeStoreProfit($query_date,$order_exchange);
        
        //求和--所有个人店铺
        $Achievements = $this->TotalSumTotal($AchievementsSmall,$AchievementsLarge);

        //方案2---使用录入的广告费
        $advertising_info = $this->advertising_info($date,$admin_id);
        $Achievements['advertising'] = $advertising_info['advertising'] ?? 0; 
        $Achievements['advertising_rate'] = $advertising_info['advertising_rate'] ?? 0; 
        
        //渠道内分配毛利
        $profit_other = $this->DistributionWithinTheChannel($query_date,$order_exchange);
        $Achievements['chananel_total_shop'] = $profit_other ?? 0;

        //方案2---使用录入的渠道分配
        $chananel_total = $this->chananel_total($date,$admin_id);
        if($chananel_total > 0){
            $Achievements['chananel_total'] = $chananel_total;
        }else{
            $Achievements['chananel_total'] = 0;
            if($Achievements['advertising_rate'] > 0 && $profit_other > 0){
                $Achievements['chananel_total'] = (float)number_format($Achievements['chananel_total_shop'] * $Achievements['advertising_rate'], 3, '.', '');
            }
        }
        
        // halt($Achievements);
        //总利润
        $Achievements['commission'] = (float)number_format((float)$Achievements['small_profit'] + (float)$Achievements['large_profit'] + $Achievements['chananel_total'] - $Achievements['advertising'], 3, '.', '');
        //纯利润
        if($Achievements['small_profit'] >= $Achievements['advertising']){
            $Achievements['small_profit'] = (float)number_format((float)$Achievements['small_profit'] - $Achievements['advertising'], 3, '.', '');
        }else if($Achievements['large_profit'] >= $Achievements['advertising']){
            $Achievements['large_profit'] = (float)number_format((float)$Achievements['large_profit'] - $Achievements['advertising'], 3, '.', '');
        }
        //按档位算提成
        $Achievements['commission_old'] = $Achievements['commission'];
        $Achievements = $this->commission($Achievements);
        //换算人民币
        
        $Achievements['commission'] = (float)number_format((float)$Achievements['commission'] * $order_exchange['dollar'], 3, '.', '');
        $Achievements['dollar'] = $order_exchange['dollar'];
        //存表
        $Achievements['admin_name'] = $nickname;
        $Achievements['admin_id'] = $admin_id;
        $Achievements['date'] = $date;
        $Achievements['timedate'] = $start_time;
        $Achievements['dollar'] = $order_exchange['dollar'] ?? 0;
        //94%销售额
        $Achievements['total_price_handle'] = (float)number_format((float)$Achievements['total_price'] * 0.94, 3, '.', '');

        Db::name('report_monthly_personal')
            ->where('date',$date)
            ->where('admin_id',$admin_id)
            ->delete();
            // halt($Achievements);
            
        Db::name('report_monthly_personal')->insert($Achievements);
        return true;
    }

    /**
    * @desc    渠道内分配毛利
    * @date    2024/9/23
    * @author  zhangheng
    */
    public function DistributionWithinTheChannel($query_date,$order_exchange)
    {
        $where = [];
        $where[]  = ['createtime', '>=', $query_date['start_time']];
        $where[]  = ['createtime', '<=', $query_date['end_time']];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];    
        $where[]  = ['shop_id', 'in', [17, 5]];
        $where[]  = ['source', 'in', ["other", "直接访问"]];

        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        $where[]  = ['disputeapi_status', 'in', ["争议赢", "暂无争议"]];

        $Achievement_other = Db::name('order_achievement')
            ->field('
                COUNT(id) as count,
                sum(freight) as freight,
                sum(material) as material,
                sum(dispute) as dispute,
                sum(total_price) as total_price
            ')
            ->where($where)
            ->select()
            ->toarray();
        $Achievement_other['count'] = $Achievement_other[0]['count'] ?? 0;
        $Achievement_other['freight'] = $Achievement_other[0]['freight'] ?? 0;
        $Achievement_other['material'] = $Achievement_other[0]['material'] ?? 0;
        $Achievement_other['dispute'] = $Achievement_other[0]['dispute'] ?? 0;
        $Achievement_other['total_price'] = $Achievement_other[0]['total_price'] ?? 0;
        
        //物流--人民币转美金
        $Achievement_other['freight'] = (float)number_format((float)$Achievement_other['freight'] / $order_exchange['dollar'], 3, '.', '');
        //采购
        $Achievement_other['material'] = (float)number_format((float)$Achievement_other['material'] / $order_exchange['dollar'], 3, '.', '');
        //打包费
        $Achievement_other['LogisticsMarkupFee'] = (float)number_format((float)$Achievement_other['count'] * $order_exchange['LogisticsMarkupFee'], 3, '.', ''); 
        //利润
        $profit_other = (float)number_format($Achievement_other['total_price'] *0.94 - $Achievement_other['freight'] - $Achievement_other['material'] - $Achievement_other['LogisticsMarkupFee'] - $Achievement_other['dispute'], 3, '.', '');
        return $profit_other;
    }

    /**
    * @desc    方案2---使用录入的广告费
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function advertising_info($date,$admin_id)
    {
        $advertising_report = Db::name('report_monthly_personal')
                ->field('advertising,advertising_rate')
                ->where('date',$date)
                ->where('admin_id',$admin_id)
                ->find();
        return $advertising_report;
    }
    /**
    * @desc    方案2---使用录入的广告费
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function chananel_total($date,$admin_id)
    {
        $chananel_total = Db::name('report_monthly_personal')
                ->field('chananel_total')
                ->where('date',$date)
                ->where('admin_id',$admin_id)
                ->find();
        return $chananel_total['chananel_total'] ?? 0;
    }
    
    /**
    * @desc    整理每月广告
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function OrganizeMonthlyAdvertisements()
    {
        $t1       = microtime(true);

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        //业绩核算
        // $date = date('Y-m', strtotime('-3 month'));
        // $midnightYesterday = strtotime($date);
        // $start_time = date("Y-m-d", $midnightYesterday);
        // $endOfYesterday = strtotime(date("Y-m-d", strtotime("$start_time +1 month"))) - 1;
        
        $where[]  = ['a.stat_time', '>=', $start_time];
        $where[]  = ['a.stat_time', '<=', $end_time]; 
        $where[] = ['a.spend', '>=', 0.001];
        $where[] = ['a.type', '=', 0];
        
        $spendTotal = Db::name('advertising')  
            ->field('  
                sum(a.spend) as spend, 
                d.nickname,
                a.admin_id
            ')  
            ->alias('a')  
            ->join('qu_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')
            ->join('qu_system_admin d', 'd.id = a.admin_id', 'left') 
            ->where($where) 
            ->group('a.admin_id')  
            ->select()->toArray();
            // halt($spendTotal);
            
        //配置
        if(!empty($spendTotal)){
            $advertisingDatas = [];
            foreach ($spendTotal as $k=>$v) {
                //添加入库
                $advertisingData = [
                    'create_time' => date('Y-m-d', time()),
                    'date' => $date,
                    'advertise_price' => $v['spend'],
                    'user_name' => $v['nickname'] ?? "未分配",
                    'user_id' => $v['admin_id'] ?? 0,
                ];
                $advertisingDatas[] = $advertisingData;
            }
            $where = [];
            $where[]  = ['date', '=', $date];
            Db::name('order_advertise_rate')
                ->where($where)
                ->delete();
            Db::name('order_advertise_rate')->insertAll($advertisingDatas);
        }
        echo PHP_EOL . "整理每月广告-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    
    /**
    * @desc    渠道内分配比例
    * @date    2024/9/21
    * @author  zhangheng
    */
    public function advertising_rate()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        //TODO匹配广告--一个月一次
        $rate = Db::name('order_advertise_rate')
            ->field('advertise_price,user_id')
            ->where('date',$date)
            ->select()->toarray();
        foreach ($rate as $kr=>$vr) {
            $update['advertising'] = $vr['advertise_price'];
            Db::name('report_monthly_personal')
                ->where('admin_id',$vr['user_id'])
                ->update($update);
        }
        
        // 清空
        // $update_empty['advertising_rate'] = 0;
        // Db::name('report_monthly_personal')->where('date',$date)->update($update_empty);

        $sources = Db::name('report_monthly_personal')
            ->field('SUM(advertising) as advertising')
            ->where('date',$date)
            ->where('source',"<>","")
            ->select()->toarray();
        $advertisings = $sources[0]['advertising'] ?? 0;
        // halt($advertisings);
            $personal = Db::name('report_monthly_personal')
                ->field('id,advertising,admin_name')
                ->where('date',$date)
                ->where('source',"<>","")
                ->select()->toarray();
            foreach ($personal as $kp=>$vp) {
                $advertising_rate = number_format((float)$vp['advertising'] / (float)$advertisings, 3, '.', '');
                if(!empty($advertising_rate)){
                    $update_rate['advertising_rate'] = $advertising_rate;
                    Db::name('report_monthly_personal')->where('id',$vp['id'])->update($update_rate);
                    echo PHP_EOL . "运营:" . $vp['admin_name'] . '完成' . PHP_EOL;
                }
            }
    }
    
    /**
    * @desc    按档位算提成
    * @date    2024/9/21
    * @author  zhangheng
    */
    public function commission($Achievements)
    {
        $profit = $Achievements['commission'];
        if(empty($profit)){
            $Achievements['commission'] = 0;
            return $Achievements;
        }
        
        //大店铺档位判断
        switch ($Achievements['source']) {
            case 'fb':
                $params['total_price'] = $profit;
                $params['channel_type'] = 1;
                $get_channel_rate = (new ShopyLogic())->get_channel_rate($params);
                break;
            case 'tt':
                $params['total_price'] = $profit;
                $params['channel_type'] = 1;
                $get_channel_rate = (new ShopyLogic())->get_channel_rate($params);
                break;
            case 'email':
                $params['total_price'] = $profit;
                $params['channel_type'] = 2;
                $get_channel_rate = (new ShopyLogic())->get_channel_rate($params);
                break;
            case 'ggad':
                $params['total_price'] = $profit;
                $params['channel_type'] = 2;
                $get_channel_rate = (new ShopyLogic())->get_channel_rate($params);
                break;
            case 'impact':
                $params['total_price'] = $profit;
                $params['channel_type'] = 2;
                $get_channel_rate = (new ShopyLogic())->get_channel_rate($params);
                break;
            default:
                $params['total_price'] = $profit;
                $params['channel_type'] = 2;
                $get_channel_rate = (new ShopyLogic())->get_channel_rate($params);
        }
        // halt($get_channel_rate);
        // $get_channel_rate = 0.03;
        if($get_channel_rate > 0){
            $profit = (float)number_format($profit * $get_channel_rate, 3, '.', '');
            $Achievements['get_channel_rate'] = $get_channel_rate;
        }else{
            $profit = 0;
            $Achievements['get_channel_rate'] = 0;
        }
        $Achievements['commission'] = $profit;
        return $Achievements;
    }
    
    /**
    * @desc    求和
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function TotalSumTotal($AchievementsSmall,$AchievementsLarge)
    {
        $Achievements = [
            'count'  => number_format((float)$AchievementsSmall['count'] + (float)$AchievementsLarge['count'], 3, '.', ''),
            'freight'  => number_format((float)$AchievementsSmall['freight'] + (float)$AchievementsLarge['freight'], 3, '.', ''),
            'material'  => number_format((float)$AchievementsSmall['material'] + (float)$AchievementsLarge['material'], 3, '.', ''),
            'dispute'  => number_format((float)$AchievementsSmall['dispute'] + (float)$AchievementsLarge['dispute'], 3, '.', ''),
            'skuquantity'  => number_format((float)$AchievementsSmall['skuquantity'] + (float)$AchievementsLarge['skuquantity'], 3, '.', ''),
            'count'  => number_format((float)$AchievementsSmall['count'] + (float)$AchievementsLarge['count'], 3, '.', ''),
            'total_price_old'  => number_format((float)$AchievementsSmall['total_price_old'] + (float)$AchievementsLarge['total_price_old'], 3, '.', ''),
            'total_price'  => number_format((float)$AchievementsSmall['total_price'] + (float)$AchievementsLarge['total_price'], 3, '.', ''),
            'advertising'  => number_format((float)$AchievementsSmall['advertising'] + (float)$AchievementsLarge['advertising'], 3, '.', ''),
            'LogisticsMarkupFee'  => number_format((float)$AchievementsSmall['LogisticsMarkupFee'] + (float)$AchievementsLarge['LogisticsMarkupFee'], 3, '.', ''),
    
            'small_profit' => $AchievementsSmall['small_profit'] ?? 0,
            'large_profit' => $AchievementsLarge['large_profit'] ?? 0,
            'advertising_rate' => $AchievementsLarge['advertising_rate'] ?? 0,
            'chananel_total' => $AchievementsLarge['chananel_total'] ?? 0,
            'source' => $AchievementsLarge['source'],
        ];  
        return $Achievements;
    }
    
    /**
    * @desc    小店铺
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function SmallShopProfit($query_date,$order_exchange){
        $where = [];
        $where[]  = ['createtime', '>=', $query_date['start_time']];
        $where[]  = ['createtime', '<=', $query_date['end_time']];
        $where[]  = ['admin_id', '=', $query_date['admin_id']];
        $where[]  = ['shop_id', 'not in', [17, 5]];

        //TODO 特殊规则 7月业绩不算WomenForSure
        $where[]  = ['shop_id', 'not in', [17, 5,10]];

        $dispute_array = Db::name('order_achievement')
            ->field('
            sum(total_price) as total_price_old,
            sum(dispute) as dispute
            ')
            ->where($where)
            ->select()
            ->toarray();
        $dispute = $dispute_array[0]['dispute'] ?? 0;
        $total_price_old = $dispute_array[0]['total_price_old'] ?? 0;
        // halt($dispute);
        
        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        //物流
        $where2  = [];
        $where2[]  = ['freight', '>', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(freight) as freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $freight = $freight_array[0]['freight'] ?? 0;

        $where2  = [];
        $where2[]  = ['freight', '<=', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(estimate_freight) as estimate_freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $estimate_freight = $freight_array[0]['estimate_freight'] ?? 0;

        $Achievement = Db::name('order_achievement')
            ->field('
                COUNT(id) as count_LogisticsMarkupFee,
                sum(material) as material,
                admin_id
            ')
            ->where($where)
            ->select()
            ->toarray();
            // halt($Achievement);
            
        $Achievements = $Achievement[0] ?? [];
        if(empty($Achievements)){
            $Achievements = [
                'count'  => 0,
                'freight' => 0,
                'material' => 0,
                'dispute' => 0,
                'skuquantity' => 0,
                'total_price_old' => 0,
                'total_price' => 0,
                'small_profit' => 0,
                'large_profit' => 0,
                'advertising_rate' => 0,
                'chananel_total' => 0,
                'commission' => 0,
                'advertising' => 0,
                'LogisticsMarkupFee' => 0,
            ];  
            return $Achievements;  
        }
        //计算销售额加两个条件
        $where[]  = ['disputeapi_status', 'in', ["争议赢", "暂无争议"]];
        $total_price = Db::name('order_achievement')
            ->field('
                COUNT(id) as count,
                sum(total_price) as total_price,
                sum(skuquantity) as skuquantity
            ')
            ->where($where)
            ->select()
            ->toarray();
        $Achievements['total_price'] = $total_price[0]['total_price'];
        $Achievements['skuquantity'] = $total_price[0]['skuquantity'];
        $Achievements['count'] = $total_price[0]['count'];

        $Achievements['total_price_old'] = $total_price_old;
        $Achievements['dispute'] = $dispute;
        $Achievements['freight'] = number_format((float)$freight + (float)$estimate_freight, 3, '.', '');
        //物流--人民币转美金
        $Achievements['freight'] = (float)number_format((float)$Achievements['freight'] / $order_exchange['dollar'], 3, '.', '');
        //采购
        $Achievements['material'] = (float)number_format((float)$Achievements['material'] / $order_exchange['dollar'], 3, '.', '');
        //打包费
        $Achievements['LogisticsMarkupFee'] = (float)number_format((float)$Achievements['count_LogisticsMarkupFee'] * $order_exchange['LogisticsMarkupFee'], 3, '.', '');
        $Achievements['advertising'] = 0;
        //利润
        $small_profit = (float)number_format($Achievements['total_price'] *0.94 - $Achievements['freight'] - $Achievements['material'] - $Achievements['LogisticsMarkupFee'] - $Achievements['dispute'] - $Achievements['advertising'], 3, '.', '');
        $Achievements['small_profit'] = $small_profit;

        return $Achievements;
    }
    /**
    * @desc    大店铺
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function LargeStoreProfit($query_date,$order_exchange){
        $where = [];
        $where[]  = ['createtime', '>=', $query_date['start_time']];
        $where[]  = ['createtime', '<=', $query_date['end_time']];
        $where[]  = ['shop_id', 'in', [17, 5]];
        $where[]  = ['admin_id', '=', $query_date['admin_id']];

        $dispute_array = Db::name('order_achievement')
            ->field('
                COUNT(id) as count_old,
                sum(total_price) as total_price_old,
                sum(dispute) as dispute
            ')
            ->where($where)
            ->select()
            ->toarray();
        $dispute = $dispute_array[0]['dispute'] ?? 0;
        $total_price_old = $dispute_array[0]['total_price_old'] ?? 0;

        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];   

        //物流
        $where2  = [];
        $where2[]  = ['freight', '>', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(freight) as freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $freight = $freight_array[0]['freight'] ?? 0;

        $where2  = [];
        $where2[]  = ['freight', '<=', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(estimate_freight) as estimate_freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $estimate_freight = $freight_array[0]['estimate_freight'] ?? 0;

        $Achievement = Db::name('order_achievement')
            ->field('
                COUNT(id) as count_LogisticsMarkupFee,
                sum(material) as material,
                admin_id,source
            ')
            ->where($where)
            ->select()
            ->toarray();
            
        $Achievements = $Achievement[0] ?? [];
        
        if(empty($Achievements)){
            $Achievements = [
                'count'  => 0,
                'freight' => 0,
                'material' => 0,
                'dispute' => 0,
                'skuquantity' => 0,
                'total_price_old' => 0,
                'total_price' => 0,
                'small_profit' => 0,
                'large_profit' => 0,
                'advertising_rate' => 0,
                'chananel_total' => 0,
                'commission' => 0,
                'advertising' => 0,
                'LogisticsMarkupFee' => 0,
                'source' => "",
            ]; 
            return $Achievements;
        }
        
        //计算销售额加两个条件
        $where[]  = ['disputeapi_status', 'in', ["争议赢", "暂无争议"]];
        // halt($where);
        
        $total_price = Db::name('order_achievement')
            ->field('
                COUNT(id) as count,
                sum(total_price) as total_price,
                sum(skuquantity) as skuquantity
            ')
            ->where($where)
            ->select()
            ->toarray();
        $Achievements['total_price'] = $total_price[0]['total_price'];
        $Achievements['skuquantity'] = $total_price[0]['skuquantity'];
        $Achievements['count'] = $total_price[0]['count'];

        $Achievements['total_price_old'] = $total_price_old;

        $Achievements['dispute'] = $dispute;
        $Achievements['freight'] = number_format((float)$freight + (float)$estimate_freight, 3, '.', '');
        //物流--人民币转美金
        $Achievements['freight'] = (float)number_format((float)$Achievements['freight'] / $order_exchange['dollar'], 3, '.', '');
        //采购
        $Achievements['material'] = (float)number_format((float)$Achievements['material'] / $order_exchange['dollar'], 3, '.', '');
        //打包费
        $Achievements['LogisticsMarkupFee'] = (float)number_format((float)$Achievements['count_LogisticsMarkupFee'] * $order_exchange['LogisticsMarkupFee'], 3, '.', '');
        
        // halt($Achievements);
        //广告
        $Achievements['advertising'] = 0;

        //利润
        $large_profit = (float)number_format($Achievements['total_price'] *0.94 - $Achievements['freight'] - $Achievements['material'] - $Achievements['LogisticsMarkupFee'] - $Achievements['dispute'] - $Achievements['advertising'], 3, '.', '');
        $Achievements['large_profit'] = $large_profit;

        
        return $Achievements;
    }
    
    
    /**
    * @desc    渠道内分配
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function WithinTheChannelAchievements($source,$query_date,$order_exchange){
        $where = [];
        $where[]  = ['createtime', '>=', $query_date['start_time']];
        $where[]  = ['createtime', '<=', $query_date['end_time']];
        $where[]  = ['shop_id', 'in', [17, 5]];

        $where[]  = ['source', '=', $source];
        $where[]  = ['admin_id', '<=', 0];

        $dispute_array = Db::name('order_achievement')
            ->field('
                sum(total_price) as total_price_old,
                sum(dispute) as dispute
            ')
            ->where($where)
            ->select()
            ->toarray();
            
        $dispute = $dispute_array[0]['dispute'] ?? 0;
        $total_price_old = $dispute_array[0]['total_price_old'] ?? 0;

        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];   

        //物流
        $where2  = [];
        $where2[]  = ['freight', '>', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(freight) as freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $freight = $freight_array[0]['freight'] ?? 0;

        $where2  = [];
        $where2[]  = ['freight', '<=', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(estimate_freight) as estimate_freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $estimate_freight = $freight_array[0]['estimate_freight'] ?? 0;

        $Achievement = Db::name('order_achievement')
            ->field('
                COUNT(id) as count_LogisticsMarkupFee,
                sum(material) as material,
                admin_id,source
            ')
            ->where($where)
            ->select()
            ->toarray();
            
        $Achievements = $Achievement[0] ?? [];
        
        if(empty($Achievements)){
            $Achievements = [
                'count'  => 0,
                'freight' => 0,
                'material' => 0,
                'dispute' => 0,
                'skuquantity' => 0,
                'total_price_old' => 0,
                'total_price' => 0,
                'small_profit' => 0,
                'large_profit' => 0,
                'advertising_rate' => 0,
                'chananel_total' => 0,
                'commission' => 0,
                'advertising' => 0,
                'LogisticsMarkupFee' => 0,
                'source' => "",
            ]; 
            return $Achievements;
        }
        
        //计算销售额加两个条件
        $where[]  = ['disputeapi_status', 'in', ["争议赢", "暂无争议"]];
        // halt($where);
        
        $total_price = Db::name('order_achievement')
            ->field('
                COUNT(id) as count,
                sum(total_price) as total_price,
                sum(skuquantity) as skuquantity
            ')
            ->where($where)
            ->select()
            ->toarray();
        $Achievements['total_price'] = $total_price[0]['total_price'];
        $Achievements['skuquantity'] = $total_price[0]['skuquantity'];
        $Achievements['count'] = $total_price[0]['count'];

        $Achievements['total_price_old'] = $total_price_old;

        $Achievements['dispute'] = $dispute;
        $Achievements['freight'] = number_format((float)$freight + (float)$estimate_freight, 3, '.', '');
        //物流--人民币转美金
        $Achievements['freight'] = (float)number_format((float)$Achievements['freight'] / $order_exchange['dollar'], 3, '.', '');
        //采购
        $Achievements['material'] = (float)number_format((float)$Achievements['material'] / $order_exchange['dollar'], 3, '.', '');
        //打包费
        $Achievements['LogisticsMarkupFee'] = (float)number_format((float)$Achievements['count_LogisticsMarkupFee'] * $order_exchange['LogisticsMarkupFee'], 3, '.', '');
        
        // halt($Achievements);
        //广告
        $Achievements['advertising'] = 0;

        //利润
        $large_profit = (float)number_format($Achievements['total_price'] *0.94 - $Achievements['freight'] - $Achievements['material'] - $Achievements['LogisticsMarkupFee'] - $Achievements['dispute'] - $Achievements['advertising'], 3, '.', '');
        $Achievements['large_profit'] = $large_profit;

        unset($Achievements['count_LogisticsMarkupFee']);
        return $Achievements;
    }

    /**
    * @desc    渠道外分配
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function DistributionOutsideTheChannelAchievements($query_date,$order_exchange){
        $where = [];
        $where[]  = ['createtime', '>=', $query_date['start_time']];
        $where[]  = ['createtime', '<=', $query_date['end_time']];
        $where[]  = ['shop_id', 'in', [17, 5]];

        $where[]  = ['source', 'in', ["other", "直接访问"]];

        $dispute_array = Db::name('order_achievement')
            ->field('
                sum(total_price) as total_price_old,
                sum(dispute) as dispute
            ')
            ->where($where)
            ->select()
            ->toarray();
            
        $dispute = $dispute_array[0]['dispute'] ?? 0;
        $total_price_old = $dispute_array[0]['total_price_old'] ?? 0;

        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];   

        //物流
        $where2  = [];
        $where2[]  = ['freight', '>', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(freight) as freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $freight = $freight_array[0]['freight'] ?? 0;

        $where2  = [];
        $where2[]  = ['freight', '<=', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(estimate_freight) as estimate_freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $estimate_freight = $freight_array[0]['estimate_freight'] ?? 0;

        $Achievement = Db::name('order_achievement')
            ->field('
                COUNT(id) as count_LogisticsMarkupFee,
                sum(material) as material,
                admin_id,source
            ')
            ->where($where)
            ->select()
            ->toarray();
            
        $Achievements = $Achievement[0] ?? [];
        
        if(empty($Achievements)){
            $Achievements = [
                'count'  => 0,
                'freight' => 0,
                'material' => 0,
                'dispute' => 0,
                'skuquantity' => 0,
                'total_price_old' => 0,
                'total_price' => 0,
                'small_profit' => 0,
                'large_profit' => 0,
                'advertising_rate' => 0,
                'chananel_total' => 0,
                'commission' => 0,
                'advertising' => 0,
                'LogisticsMarkupFee' => 0,
                'source' => "",
            ]; 
            return $Achievements;
        }
        
        //计算销售额加两个条件
        $where[]  = ['disputeapi_status', 'in', ["争议赢", "暂无争议"]];
        // halt($where);
        
        $total_price = Db::name('order_achievement')
            ->field('
                COUNT(id) as count,
                sum(total_price) as total_price,
                sum(skuquantity) as skuquantity
            ')
            ->where($where)
            ->select()
            ->toarray();
        $Achievements['total_price'] = $total_price[0]['total_price'];
        $Achievements['skuquantity'] = $total_price[0]['skuquantity'];
        $Achievements['count'] = $total_price[0]['count'];

        $Achievements['total_price_old'] = $total_price_old;

        $Achievements['dispute'] = $dispute;
        $Achievements['freight'] = number_format((float)$freight + (float)$estimate_freight, 3, '.', '');
        //物流--人民币转美金
        $Achievements['freight'] = (float)number_format((float)$Achievements['freight'] / $order_exchange['dollar'], 3, '.', '');
        //采购
        $Achievements['material'] = (float)number_format((float)$Achievements['material'] / $order_exchange['dollar'], 3, '.', '');
        //打包费
        $Achievements['LogisticsMarkupFee'] = (float)number_format((float)$Achievements['count_LogisticsMarkupFee'] * $order_exchange['LogisticsMarkupFee'], 3, '.', '');
        
        // halt($Achievements);
        //广告
        $Achievements['advertising'] = 0;

        //利润
        $large_profit = (float)number_format($Achievements['total_price'] *0.94 - $Achievements['freight'] - $Achievements['material'] - $Achievements['LogisticsMarkupFee'] - $Achievements['dispute'] - $Achievements['advertising'], 3, '.', '');
        $Achievements['large_profit'] = $large_profit;

        unset($Achievements['count_LogisticsMarkupFee']);
        return $Achievements;
    }

    /**
    * @desc    渠道外分配
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function SmallShopNotAllocatedAchievements($shop_id,$query_date,$order_exchange){
        $where = [];
        $where[]  = ['createtime', '>=', $query_date['start_time']];
        $where[]  = ['createtime', '<=', $query_date['end_time']];
        $where[]  = ['shop_id', '=', $shop_id];
        $where[]  = ['admin_id', '<',0];

        $dispute_array = Db::name('order_achievement')
            ->field('
                sum(total_price) as total_price_old,
                sum(dispute) as dispute
            ')
            ->where($where)
            ->select()
            ->toarray();
            
        $dispute = $dispute_array[0]['dispute'] ?? 0;
        $total_price_old = $dispute_array[0]['total_price_old'] ?? 0;

        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];   

        //物流
        $where2  = [];
        $where2[]  = ['freight', '>', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(freight) as freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $freight = $freight_array[0]['freight'] ?? 0;

        $where2  = [];
        $where2[]  = ['freight', '<=', 0];
        $freight_array = Db::name('order_achievement')
            ->field('
                sum(estimate_freight) as estimate_freight
            ')
            ->where($where)
            ->where($where2)
            ->select()
            ->toarray();
        $estimate_freight = $freight_array[0]['estimate_freight'] ?? 0;

        $Achievement = Db::name('order_achievement')
            ->field('
                COUNT(id) as count_LogisticsMarkupFee,
                sum(material) as material,
                admin_id,source
            ')
            ->where($where)
            ->select()
            ->toarray();
            
        $Achievements = $Achievement[0] ?? [];
        
        if(empty($Achievements)){
            $Achievements = [
                'count'  => 0,
                'freight' => 0,
                'material' => 0,
                'dispute' => 0,
                'skuquantity' => 0,
                'total_price_old' => 0,
                'total_price' => 0,
                'small_profit' => 0,
                'large_profit' => 0,
                'advertising_rate' => 0,
                'chananel_total' => 0,
                'commission' => 0,
                'advertising' => 0,
                'LogisticsMarkupFee' => 0,
                'source' => "",
            ]; 
            return $Achievements;
        }
        
        //计算销售额加两个条件
        $where[]  = ['disputeapi_status', 'in', ["争议赢", "暂无争议"]];
        // halt($where);
        
        $total_price = Db::name('order_achievement')
            ->field('
                COUNT(id) as count,
                sum(total_price) as total_price,
                sum(skuquantity) as skuquantity
            ')
            ->where($where)
            ->select()
            ->toarray();
        $Achievements['total_price'] = $total_price[0]['total_price'];
        $Achievements['skuquantity'] = $total_price[0]['skuquantity'];
        $Achievements['count'] = $total_price[0]['count'];

        $Achievements['total_price_old'] = $total_price_old;

        $Achievements['dispute'] = $dispute;
        $Achievements['freight'] = number_format((float)$freight + (float)$estimate_freight, 3, '.', '');
        //物流--人民币转美金
        $Achievements['freight'] = (float)number_format((float)$Achievements['freight'] / $order_exchange['dollar'], 3, '.', '');
        //采购
        $Achievements['material'] = (float)number_format((float)$Achievements['material'] / $order_exchange['dollar'], 3, '.', '');
        //打包费
        $Achievements['LogisticsMarkupFee'] = (float)number_format((float)$Achievements['count_LogisticsMarkupFee'] * $order_exchange['LogisticsMarkupFee'], 3, '.', '');
        
        // halt($Achievements);
        //广告
        $Achievements['advertising'] = 0;

        //利润
        $large_profit = (float)number_format($Achievements['total_price'] *0.94 - $Achievements['freight'] - $Achievements['material'] - $Achievements['LogisticsMarkupFee'] - $Achievements['dispute'] - $Achievements['advertising'], 3, '.', '');
        $Achievements['large_profit'] = $large_profit;

        unset($Achievements['count_LogisticsMarkupFee']);
        return $Achievements;
    }
    /**
    * @desc    相关运营归属记录
    * @date    2024/8/10
    * @author  zhangheng
    */
    public function OperationOwnership($query_date)
    {
        $lists = Db::name('shops_admin')  
            ->where(function ($query) use ($query_date) {  
                $query->where('createtime', '<=', $query_date['end_time'])  
                    ->where('updatetime', '>=', $query_date['start_time'])  
                    ->where('admin_id', '=', $query_date['admin_id'])
                    ->where('status', '=', 0);  
            })  
            ->whereOr(function ($query) use ($query_date) {  
                $query->where('createtime', '<=', $query_date['end_time'])  
                ->where('admin_id', '=', $query_date['admin_id'])
                ->where('status', '=', 1);  
            })
            ->select()->toArray();
        return $lists;
    }

    /**
    * @desc    单人店铺业绩
    * @date    2024/8/10
    * @author  zhangheng
    */
    public function SinglePersonStorePerformance($shops_admin)
    {
        if(in_array($shops_admin['shop_id'],[5,17])){
            return true;
        }
        $where[]  = ['shop_id', '=', $shops_admin['shop_id']];
        $where[]  = ['createtime', '>=', $shops_admin['createtime']];
        $where[]  = ['createtime', '<=', $shops_admin['updatetime']];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        $update['admin_id'] = $shops_admin['admin_id'];
        $lists = Db::name('order_achievement')
            ->where($where)
            ->update($update);
            
        return $lists;
    }

    /**
    * @desc    多人店铺业绩
    * @date    2024/8/10
    * @author  zhangheng
    */
    public function MultiPersonStorePerformance($shops_admin)
    {
        if(in_array($shops_admin['shop_id'],[5,17])){
            return true;
        }
        $where[]  = ['shop_id', '=', $shops_admin['shop_id']];
        $where[]  = ['createtime', '>=', $shops_admin['createtime']];
        $where[]  = ['createtime', '<=', $shops_admin['updatetime']];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        if(!empty($shops_admin['label'])){
            $where[] = array('tags', 'LIKE', '%' . trim($shops_admin['label']) . '%');
            $update['admin_id'] = $shops_admin['admin_id'];
            $lists = Db::name('order_achievement')
                ->where($where)
                ->update($update);
        }else{
            $shops_admin_other = Db::name('shops_admin')
                ->field('label')
                ->where('shop_id',$shops_admin['shop_id'])
                ->where('admin_id',"<>",$shops_admin['admin_id'])
                ->select()->toarray();
            foreach ($shops_admin_other as $label) {  
                $where[] = ['tags', 'NOT LIKE', '%' . $label['label'] . '%'];  
            }
            $update['admin_id'] = $shops_admin['admin_id'];
            $lists = Db::name('order_achievement')
                ->where($where)
                ->update($update);
        }
        return $lists;
    }

    /**
    * @desc    重新整理时间段
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ReorganizeTimePeriods($shops_admin,$query_date)
    {
        if($shops_admin['createtime'] < $query_date['start_time']){
            $shops_admin['createtime'] = $query_date['start_time'];
        }
        if($shops_admin['updatetime'] == 0){
            $shops_admin['updatetime'] = $query_date['end_time'];
        }elseif($shops_admin['updatetime'] > $query_date['end_time']){
            $shops_admin['updatetime'] = $query_date['end_time'];
        }
        return $shops_admin;
    }
    
    /**
    * @desc    每天统计广告运营消耗
    * @date    2024/8/12
    * @author  zhangheng
    */
    public function DailyStatisticsOfAdv_admin()
    {
        $t1       = microtime(true);
        $lastday = date('Y-m-d', strtotime('-3 day') - timezone());
        $endday = date('Y-m-d', strtotime('-1 day') - timezone());

        $midnightYesterday = strtotime($lastday);
        $endOfYesterday  = strtotime($endday);     

        //业绩核算
        // $date = date('Y-m', strtotime('-3 month'));
        // $midnightYesterday = strtotime($date);
        // $start_time = date("Y-m-d", $midnightYesterday);
        // $endOfYesterday = strtotime(date("Y-m-d", strtotime("$start_time +1 month"))) - 1;

        //月度统计
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        $where[]  = ['a.stat_time', '>=', $start_time];
        $where[]  = ['a.stat_time', '<=', $end_time]; 

        // $where[]  = ['a.stat_time', '>=', $midnightYesterday];
        // $where[]  = ['a.stat_time', '<=', $endOfYesterday]; 

        $where[] = ['a.spend', '>=', 0.001];
        $where[] = ['a.type', '=', 0];
        // halt($where);

        //匹配开始
        $count = Db::name('advertising')  
            ->alias('a')  
            ->where($where) 
            ->count();
            
        $executedCount = 0;
        $spendTotal = Db::name('advertising')  
            ->field('  
                a.id,
                a.advertiser_id,
                a.stat_time_day,
                COALESCE(c.admin_id, c2.admin_id) as admin_id_coalesced,
                COALESCE(c.shop_id, c2.shop_id) as shop_id_coalesced
            ')  
            ->alias('a')  
            ->join('qu_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')  
            ->join('qu_advaccount_admin c', '  
                c.advertiser_id = b.advertiser_id AND  
                c.createtime <= a.stat_time AND  
                c.updatetime > a.stat_time AND  
                c.status = 0', 'left')  
            ->join('qu_advaccount_admin c2', '  
                c2.advertiser_id = b.advertiser_id AND  
                c2.createtime <= a.stat_time AND  
                c2.status = 1', 'left')  
            ->where($where) 
            ->group('a.id')
            ->select()->toArray();
        foreach ($spendTotal as $key => $value) {  
            //修改shop_id
            Db::name('advertising')
                ->where('id',$value['id'])
                ->update([
                    'admin_id' => $value['admin_id_coalesced'] ?? 0,
                    'shop_id' => $value['shop_id_coalesced'] ?? 0
                ]);
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }

        // 检查
        $where['shop_id'] = 0;
        $inspect = Db::name('advertising')  
            ->field('  
                a.id,
                a.stat_time_day,
                b.info,
                a.advertiser_id,admin_id,shop_id
            ')  
            ->alias('a')  
            ->join('qu_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')
            ->where($where)  
            ->select()->toArray();
        if(!empty($inspect)){
            echo PHP_EOL . "广告账户分配有遗漏" . PHP_EOL;
            foreach ($inspect as $k=>$v) {
                // halt($v);
                echo PHP_EOL . "".$v['stat_time_day']."广告id:" . $v['advertiser_id'] . ',备注：'.$v['info']."" . PHP_EOL;
            }
        }else{
            $msg = "广告账户分配没有遗漏";
            halt($msg);
        }

        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
    * @desc    广告账户分配到店铺--检查
    * @date    2024/8/12
    * @author  zhangheng
    */
    public function Adv_inspect()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $where[]  = ['a.stat_time', '>=', $start_time];
        $where[]  = ['a.stat_time', '<=', $end_time]; 
        $where[] = ['a.spend', '>=', 0.001];
        $where[] = ['a.type', '=', 0];
        
        // 检查
        $where['shop_id'] = 0;
        $inspect = Db::name('advertising')  
            ->field('  
                a.id,
                a.stat_time_day,
                a.spend,
                b.info,
                a.advertiser_id,admin_id,shop_id
            ')  
            ->alias('a')  
            ->join('qu_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')
            ->where($where)  
            ->order('stat_time_day desc')
            ->select()->toArray();
        if(!empty($inspect)){
            $return[] = [
                'msg' => "广告账户分配有遗漏",
                'status' => 0,//0失败 1通过
            ];
            foreach ($inspect as $k=>$v) {
                $v['stat_time_day'] = date('m月d号',strtotime($v['stat_time_day']));
                $return[] = [
                    'msg' => $v['stat_time_day']."有".$v['spend']."消耗-广告id:" . $v['advertiser_id'] . ',账户备注：'.$v['info'],
                    'status' => 0,//0失败 1通过
                ];
                $return_adv[$v['advertiser_id']] = $v['advertiser_id'];
            }
            //提取所有key值
            // $return_adv = array_keys($return_adv);
            // halt($return_adv);
        }else{
            $return[] = [
                'msg' => "广告账户分配没有遗漏",
                'status' => 1,//0失败 1通过
            ];
        }
        return $return;

    }
    /**
    * @desc    店铺分配给运营--核对--检查
    * @date    2024/10/19
    * @author  zhangheng
    */
    public function shop_admin_inspect()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $where[]  = ['a.createtime', '>=', $start_time];
        $where[]  = ['a.createtime', '<=', $end_time]; 
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[] = ['a.admin_id', '<', 1];
        $where[]  = ['a.shop_id', 'not in', [17, 5]];

        //TODO 特殊规则 7月业绩不算WomenForSure
        if($date == '2024-07'){
            $where[]  = ['a.shop_id', 'not in', [17, 5,10]];
        }
        
        // 检查
        $inspect = Db::name('order_achievement')  
            ->field(' 
                count(a.id) as count,
                a.shop_id,
                b.name
            ')  
            ->alias('a')  
            ->join('qu_shops b', 'b.id = a.shop_id', 'left')
            ->where($where)
            ->group('a.shop_id')
            ->select()->toArray();
        if(!empty($inspect)){
            $return[] = [
                'msg' => "店铺分配有遗漏",
                'status' => 0,//0失败 1通过
            ];
            foreach ($inspect as $k=>$v) {
                $return[] = [
                    'msg' => $v['name']."店铺分配遗漏".$v['count']."单",
                    'status' => 0,//0失败 1通过
                ];
            }
        }else{
            $return[] = [
                'msg' => "店铺分配没有遗漏",
                'status' => 1,//0失败 1通过
            ];
        }
        return $return;

    }
    /**
    * @desc    每天统计广告运营消耗
    * @date    2024/8/12
    * @author  zhangheng
    */
    public function DailyStatisticsOfAdv()
    {
        $t1       = microtime(true);
        $lastday = date('Y-m-d', strtotime('-30 day') - timezone());
        $endday = date('Y-m-d', strtotime('-1 day') - timezone());

        $midnightYesterday = strtotime($lastday);
        $endOfYesterday  = strtotime($endday);     

        //业绩核算
        // $date = date('Y-m', strtotime('-3 month'));
        // $midnightYesterday = strtotime($date);
        // $start_time = date("Y-m-d", $midnightYesterday);
        // $endOfYesterday = strtotime(date("Y-m-d", strtotime("$start_time +1 month"))) - 1;
        
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        $where[]  = ['a.stat_time', '>=', $start_time];
        $where[]  = ['a.stat_time', '<=', $end_time]; 

        // $where[]  = ['a.stat_time', '>=', $midnightYesterday];
        // $where[]  = ['a.stat_time', '<=', $endOfYesterday]; 
        $where[] = ['a.spend', '>=', 0.001];
        $where[] = ['a.type', '=', 0];
        
        $spendTotal = Db::name('advertising')  
            ->field('  
                sum(a.spend) as spend,  
                a.platform_id as platform,  
                DATE(FROM_UNIXTIME(a.stat_time)) as date, 
                d.nickname, 
                a.admin_id
            ')  
            ->alias('a') 
            ->join('qu_system_admin d', 'd.id = a.admin_id', 'left') 
            ->where($where)
            ->group('a.platform_id,admin_id, DATE(FROM_UNIXTIME(a.stat_time))')  
            ->select()->toArray();
        
        //配置
        if(!empty($spendTotal)){
            $advertisingDatas = [];
            foreach ($spendTotal as $k=>$v) {
                //添加入库
                $advertisingData = [
                    'date' => $v['date'],
                    'time' => strtotime($v['date']),
                    'spend' => $v['spend'],
                    'platform' => $v['platform'],
                    'name' => $v['nickname'] ?? "未分配",
                    'admin_id' => $v['admin_id'] ?? 0,
                ];
                $advertisingDatas[] = $advertisingData;
            }
            $where = [];
            $where[]  = ['time', '>=', $midnightYesterday];
            $where[]  = ['time', '<=', $endOfYesterday]; 
            // halt($advertisingDatas);
            Db::name('advertising_report')
                ->where($where)
                ->delete();
            Db::name('advertising_report')->insertAll($advertisingDatas);
        }
        echo PHP_EOL . "统计每天广告运营消耗执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
    * @desc    财务报表核对
    * @date    2024/8/21
    * @author  zhangheng
    */
    public function FinancialStatementVerification()
    {
        //准备工作
        // $PreparationWork = $this->PreparationWork();
        //总订单
        // $TotalOrder = $this->TotalOrder();
        // halt($TotalOrder);
        //物流账单
        // $LogisticsBill = $this->LogisticsBill();
        //物流成本
        // $LogisticsCost = $this->LogisticsCost();
        // halt($LogisticsCost);
        //采购账单
        // $ProcurementBill = $this->ProcurementBill();
        // halt($ProcurementBill);
        //采购成本
        // $ProcurementCost = $this->ProcurementCost();
        // halt($ProcurementCost);
        //争议成本
        // $DisputeCostlast = $this->DisputeCostlast();//统一争议数据
        
        
        // $DisputeCost = $this->DisputeCost();
        // halt($DisputeCost);

        // $mergedArray = array_merge($PreparationWork, $TotalOrder,$LogisticsBill,$LogisticsCost,$ProcurementBill,$ProcurementCost,$DisputeCost);
        //广告成本
        //店铺分配给运营--核对
        // $shop_admin = $this->shop_admin_inspect();
        // halt($shop_admin);
        
        //每天统计广告运营消耗
        // $this->DailyStatisticsOfAdv_admin();
        //广告运营--核对
        $Adv_inspect = $this->Adv_inspect();
        halt($Adv_inspect);
        
        // halt($AdvertisingCost);
        //订单标签匹配
        // $OrderTagMatching = $this->OrderTagMatching();
        // halt($OrderTagMatching);

        $t1       = microtime(true);
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    
    /**
    * @desc    准备工作
    * @date    2024/8/21
    * @author  zhangheng
    */
    public function PreparationWork()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();
        if(empty($order_exchange)){
            $return[] = [
                'msg' => "请填写".$date_msg."费用预估值",
                'status' => 0,//0失败 1通过
            ];
            return $return;
        }else{
            $return[] = [
                'msg' => $date_msg."美金汇率".$order_exchange['dollar'],
                'status' => 1,//0失败 1通过
            ];
            $return[] = [
                'msg' => $date_msg."打包费$".$order_exchange['LogisticsMarkupFee'],
                'status' => 1,//0失败 1通过
            ];
            return $return;
        }
    }

    /**
    * @desc    总订单
    * @date    2024/8/21
    * @author  zhangheng
    */
    public function TotalOrder()
    {   
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        
        $order_achievement = Db::name('order_achievement')
            ->field('
                COUNT(id) as count
            ')
            ->where($where)
            ->select()->toarray();

        if(empty($order_achievement)){
            $return[] = [
                'msg' => $date_msg."暂无订单数据",
                'status' => 0,//0失败 1通过
            ];
            return $return;
        }else{
            $order_achievements = $order_achievement[0];
            $return[] = [
                'msg' => $date_msg."总单量".$order_achievements['count'],
                'status' => 1,//0失败 1通过
            ];
            //业绩口径
            $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
            $where[]  = ['disputeapi_status', 'in', ["争议赢", "暂无争议"]];
            $Achievement_other = Db::name('order_achievement')
                ->field('
                    COUNT(id) as count,
                    sum(total_price) as total_price,
                    sum(skuquantity) as skuquantity
                ')
                ->where($where)
                ->select()
                ->toarray();
            $order_achievements = $Achievement_other[0] ?? [];
            // halt($order_achievements);
            if(!empty($order_achievements)){
                $return[] = [
                    'msg' => $date_msg."计算业绩单量".$order_achievements['count'],
                    'status' => 1,//0失败 1通过
                ];
                // $return[] = [
                //     'msg' => $date_msg."销售额$".$order_achievements['total_price'],
                //     'status' => 1,//0失败 1通过
                // ];
                $return[] = [
                    'msg' => $date_msg."发货件数".$order_achievements['skuquantity'],
                    'status' => 1,//0失败 1通过
                ];
            } 
            return $return;
        }
    }
    
    /**
    * @desc    物流账单
    * @date    2024/9/19
    * @author  zhangheng
    */
    public function LogisticsBill()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $logistics = Db::name('ordercheck_logistics')
            ->field('COUNT(id) as quantity,tracking_company_number')
            ->where('date',$date)
            ->group('tracking_company_number')
            ->select()->toarray();
        foreach ($logistics as &$v) {
            $v['tracking_company_number'] = $this->switch_number($v['tracking_company_number']);
        }
            
        if(empty($logistics)){
            $return[] = [
                'msg' => $date_msg."物流账单未导入",
                'status' => 0,//0失败 1通过
            ];
            return $return;
        }else{
            foreach ($logistics as $kl=>$vl) {
                $return[] = [
                    'msg' => $date_msg."".$vl['tracking_company_number']."物流账单".$vl['quantity']."条",
                    'status' => 1,//0失败 1通过
                ];
            }
            return $return;
        }
    }
    /**
    * @desc    物流成本
    * @date    2024/8/21
    * @author  zhangheng
    */
    public function LogisticsCost()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        $countTheSum = Db::name('order_achievement')
            ->where($where)
            ->count();
        $return[] = [
            'msg' => $date_msg."总共有".$countTheSum."单物流费",
            'status' => 1,//0失败 1通过
        ];

        $count = Db::name('order_achievement')
            ->where($where)
            ->where("freight", '<=', 0)
            ->count();
            // halt($count);
        if($count > 0){
            $return[] = [
                'msg' => $date_msg."有".$count."单物流费需要预估",
                'status' => 1,//0失败 1通过
            ];
        }

        $count = Db::name('order_achievement')
            ->where($where)
            ->where("freight", '<=', 0)
            ->where("estimate_freight", '<=', 0)
            ->count();
        if($count > 0){
            $return[] = [
                'msg' => $date_msg."有".$count."单超过指定范围",
                'status' => 0,//0失败 1通过
            ];
        }else{
            $return[] = [
                'msg' => $date_msg."没有物流费超过指定范围",
                'status' => 1,//0失败 1通过
            ];
        }
        $return[] = [
            'msg' => $date_msg."物流费用正常",
            'status' => 1,//0失败 1通过
        ];
        return $return;
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function switch_number($tracking_company_number)
    {
        switch ($tracking_company_number) {
            case '1':
                $tracking_company_number = '闪电猴';
                break;
            case '2':
                $tracking_company_number = '递四方';
                break;
            case '3':
                $tracking_company_number = '全程无忧';
                break;
            case '4':
                $tracking_company_number = '顺丰';
                break;
            default:
        }
        return $tracking_company_number;
    }
    
    /**
    * @desc    订单标签匹配
    * @date    2024/9/19
    * @author  zhangheng
    */
    public function OrderTagMatching()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        $lists = Db::name('order_source')
            ->field('tag_source,tag_campaign')
            ->where($where)
            ->group('tag_campaign')
            ->order('tag_source desc')
            ->select()->toarray();

        foreach ($lists as $k=>$v) {
            $lists[$k]['tag_source'] = (new OrderSourceLogic())->tag_source($v['tag_source']);
            $lists[$k]['tag_campaign'] = (new OrderSourceLogic())->tag_campaign($v['tag_campaign']);
        }
            
        return $lists;
    }
    /**
    * @desc    采购成本
    * @date    2024/8/21
    * @author  zhangheng
    */
    public function ProcurementBill()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $spucost = Db::name('ordercheck_spucost')
            ->where('date',$date)
            ->count();
        if(empty($spucost)){
            $return[] = [
                'msg' => $date_msg."采购账单未生成",
                'status' => 0,//0失败 1通过
            ];
        }else{
            $return[] = [
                'msg' => $date_msg."SPU成本有".$spucost."条",
                'status' => 1,//0失败 1通过
            ];
        }
        
        $spucost = Db::name('ordercheck_spucost')
            ->where('date',$date)
            ->where('material',"<=",0)
            ->count();

        // $spucost = Db::name('ordercheck_spucost')
        //     ->where('date',$date)
        //     ->where('material',"<=",0)
        //     ->select()->toarray();
        //     halt($spucost);

        if($spucost > 0){
            $return[] = [
                'msg' => $date_msg."SPU成本为空的有".$spucost."条",
                'status' => 0,//0失败 1通过
            ];    
        }
        // halt($return);
        return $return;
    }
    /**
    * @desc    采购成本
    * @date    2024/8/21
    * @author  zhangheng
    */
    public function ProcurementCost()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];

        $ordercheck_spucost = Db::name('ordercheck_spucost')
            ->where('date',$date)
            ->order('material asc')
            ->find();
        $material = $ordercheck_spucost['material'] ?? 0;
        
        $countTheSum = Db::name('order_achievement')
            ->where($where)
            ->count();
        $return[] = [
            'msg' => $date_msg."总共有".$countTheSum."单采购费",
            'status' => 1,//0失败 1通过
        ];

        $count = Db::name('order_achievement')
            ->where($where)
            ->where("material", '<=', $material)
            ->count();
            
        if($count > 0){
            $return[] = [
                'msg' => $date_msg."有".$count."单超过指定范围",
                'status' => 0,//0失败 1通过
            ];
            // $order_achievements = Db::name('order_achievement')
            //     ->field('order_id,material,sku,total_price')
            //     ->where($where)
            //     ->where("material", '<=', $material)
            //     ->select()->toarray();
            // if ($order_achievements) {
            //     foreach ($order_achievements as $k=>$v) {
            //         $material_total = 0;
            //         $order_info = Db::name('order_info')
            //             ->field('product_id,quantity')
            //             ->where('order_id',$v['order_id'])
            //             ->select()->toarray();
            //         foreach ($order_info as $ko=>$vo) {
            //             $order_infos = Db::name('order_info')
            //                 ->field('material_total')
            //                 ->where('product_id',$vo['product_id'])
            //                 ->where('quantity',$vo['quantity'])
            //                 ->order('material_total desc')
            //                 ->find();
            //             $material_total += $order_infos['material_total'] ?? 0;
            //         }
            //         $update_material['material'] = $material_total;
            //         $update_material['material_status'] = "手动添加成本";
            //         // halt($update_material);
            //         Db::name('order_achievement')->where('order_id', $v['order_id'])->update($update_material);
            //     }
            // }
        }else{
            $return[] = [
                'msg' => $date_msg."没有采购费超过指定范围",
                'status' => 1,//0失败 1通过
            ];
        }
        $return[] = [
            'msg' => $date_msg."采购成本正常",
            'status' => 1,//0失败 1通过
        ];
        return $return;
    }

    /**
    * @desc    争议成本
    * @date    2024/9/19
    * @author  zhangheng
    */
    public function DisputeCostlast()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 

        //afterpay
        // $lists = Db::name('order_dispute_afterpay')
        //     ->field('type,order_id')
        //     ->where($where)
        //     ->where('order_id',"<>","")
        //     ->group('order_id')
        //     ->select()->toarray();
        // $executedCount = 0;
        // foreach ($lists as $k=>$v) {
        //     $count = Db::name('order_achievement')
        //         ->where($where)
        //         ->where('order_id',$v['order_id'])
        //         ->where('disputeapi_status',"<>","暂无争议")
        //         ->find();
        //     if(empty($count)){
        //         halt($count);
        //     }
        //     $executedCount++;
        //     echo PHP_EOL . "afterpay已执行:" . $executedCount . '条' . PHP_EOL;
        // }

        //order_dispute_api
        // $lists = Db::name('order_dispute_api')
        //     ->field('order_id')
        //     ->where($where)
        //     ->where('order_id',"<>","")
        //     ->group('order_id')
        //     ->select()->toarray();
        // $executedCount = 0;
        // foreach ($lists as $k=>$v) {
        //     $count = Db::name('order_achievement')
        //         ->where($where)
        //         ->where('order_id',$v['order_id'])
        //         ->where('disputeapi_status',"<>","暂无争议")
        //         ->find();
        //     if(empty($count)){
        //         halt($v);
        //     }
        //     $executedCount++;
        //     echo PHP_EOL . "dispute_api已执行:" . $executedCount . '条' . PHP_EOL;
        // }

        //order_dispute_paypal
        // $lists = Db::name('order_dispute_paypal')
        //     ->field('order_id,status,type')
        //     ->where($where)
        //     ->where('order_id',"<>","")
        //     ->group('order_id')
        //     ->select()->toarray();
        // $executedCount = 0;
        // $executedCountsu = 0;
        // foreach ($lists as $k=>$v) {
        //     $count = Db::name('order_achievement')
        //         ->where($where)
        //         ->where('order_id',$v['order_id'])
        //         ->where('disputeapi_status',"<>","暂无争议")
        //         ->find();
        //     if(empty($count)){
        //         //修改争议金额
        //         $v['status'] = $this->ChangeState($v['status'],'paypal');
        //         $v['dispute'] = $this->ChangeAmount($v['status'],'paypal');
        //         $update_achievement = [
        //             'order_id' => $v['order_id'],
        //             'disputeapi_type' => $v['type'],
        //             'disputeapi_status' => $v['status'] ??"暂无争议",
        //             'dispute' => $v['dispute'],
        //         ];
        //         Db::name('order_achievement')
        //             ->where('order_id',$v['order_id'])
        //             ->update($update_achievement);
        //         $executedCountsu++;
        //     }
        //     $executedCount++;
        //     echo PHP_EOL . "paypal已执行:" . $executedCount . '条,修改'.$executedCountsu."条" . PHP_EOL;
        // }
        
        // $lists = Db::name('order_dispute_stripe')
        //     ->field('order_id,status,type')
        //     ->where($where)
        //     ->where('order_id',"<>","")
        //     ->group('order_id')
        //     ->select()->toarray();
        // $executedCount = 0;
        // $executedCountsu = 0;
        // foreach ($lists as $k=>$v) {
        //     $count = Db::name('order_achievement')
        //         ->where($where)
        //         ->where('order_id',$v['order_id'])
        //         ->where('disputeapi_status',"<>","暂无争议")
        //         ->find();
        //     if(empty($count)){
        //         //修改争议金额
        //         $v['status'] = $this->ChangeState($v['status'],'paypal');
        //         $v['dispute'] = $this->ChangeAmount($v['status'],'paypal');
        //         $update_achievement = [
        //             'order_id' => $v['order_id'],
        //             'disputeapi_type' => $v['type'],
        //             'disputeapi_status' => $v['status'] ??"暂无争议",
        //             'dispute' => $v['dispute'],
        //         ];
        //         Db::name('order_achievement')
        //             ->where('order_id',$v['order_id'])
        //             ->update($update_achievement);
        //         $executedCountsu++;
        //     }
        //     $executedCount++;
        //     echo PHP_EOL . "stripe已执行:" . $executedCount . '条,修改'.$executedCountsu."条" . PHP_EOL;
        // }

// 'order_id' => $v['order_id'],
// 'disputeapi_type' => $v['type'],
// 'disputeapi_status' => $v['status'],
// 'dispute' => $v['dispute'],
        $count = Db::name('order_achievement')
            ->field('COUNT(id) as num,disputeapi_type')
            ->where($where)
            ->where('disputeapi_status',"<>","暂无争议")
            ->where('disputeapi_type',"<>","导入")
            ->group('disputeapi_type')
            ->select()->toarray();
            halt($count);
        return $return;
    }
    /**
    * @desc    争议成本
    * @date    2024/9/19
    * @author  zhangheng
    */
    public function DisputeCost()
    {
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 

        $counts = Db::name('order_achievement')
            ->field('COUNT(id) as num,disputeapi_type')
            ->where($where)
            ->where('disputeapi_status',"<>","暂无争议")
            ->where('disputeapi_type',"<>","导入")
            ->group('disputeapi_type')
            ->select()->toarray();
        $nums = 0;
        foreach ($counts as $k=>$v) {
            $return[] = [
                'msg' => $date_msg."".$v['disputeapi_type']."平台有".$v['num']."单争议信息",
                'status' => 1,//0失败 1通过
            ];
            $nums += $v['num'];
        }
        $return[] = [
            'msg' => $date_msg."共".$nums."单争议信息",
            'status' => 1,//0失败 1通过
        ];
        $return[] = [
            'msg' => $date_msg."争议成本正常",
            'status' => 1,//0失败 1通过
        ];
        return $return;
    }
    
    //争议数据对应到订单Stripe
    public function DisputeToOrdersStripe(){
        $t1       = microtime(true);
        $count = Db::name('order_dispute_stripe')
            // ->where('order_id',"<=",0)
            ->where('create_time',">=",date('Y-m-d', strtotime('-3 month')))
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_stripe')
                ->field('
                        id,
                        api_type,
                        type,
                        status,
                        order_id,create_time,
                        payment_intent
                    ')
                // ->where('order_id',"<=",0)
                ->where('create_time',">=",date('Y-m-d', strtotime('-3 month')))
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                if(!empty($v['order_id'])){
                    //修改争议金额
                    $v['status'] = $this->ChangeState($v['status'],'stripe');
                    $v['dispute'] = $this->ChangeAmount($v['status'],'stripe');
                    $update_achievement = [
                        'order_id' => $v['order_id'],
                        'disputeapi_type' => $v['type'],
                        'disputeapi_status' => $v['status'] ??"暂无争议",
                        'dispute' => $v['dispute'],
                    ];
                    Db::name('order_achievement')
                        ->where('order_id',$v['order_id'])
                        ->update($update_achievement);

                    $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                    $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                    $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                    //更新会话
                    if(!empty($order_customer['email'])){
                        $conversations = Db::name('conversations')
                            ->where('email',$order_customer['email'])
                            ->count();
                    }else{
                        $conversations = 0;
                    }
                    $update = [
                        'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                        'conversations' => $conversations,
                        'email' => $order_customer['email'] ?? "",
                        'shop_id' => $order_achievement['shop_id'] ?? "",
                        'order_name' => $order_achievement['name'] ?? "",
                        'financial_status' => $order_achievement['financial_status'] ?? "",
                        'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                        'tracking_number' => $order_achievement['tracking_number'] ?? "",
                        'disputetime' => strtotime($v['create_time']),
                    ];
                    Db::name('order_dispute_stripe')
                        ->where('id',$v['id'])
                        ->update($update);

                    $executedCountsu++;
                }else{
                    $order_transactions = Db::name('order_transactions')
                        ->field('
                            order_id,
                            shop_id
                        ')
                        ->where('authorization',$v['payment_intent'])
                        ->find();
                        
                    if(!empty($order_transactions)){

                        $order = Db::name('order')->where('order_id',$order_transactions['order_id'])->find();
                        if(!empty($order)){
                            $order_transactions['name'] = $order['name'];
                            $order_transactions['createtime'] = $order['createtime'];
                        }
                        $order_achievement = Db::name('order_achievement')->where('order_id',$order_transactions['order_id'])->find();
                        $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                        $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                        //找到争议
                        $update = [
                            'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                            'email' => $order_customer['email'] ?? "",
                            'order_id' => $order_transactions['order_id'],
                            'createtime' => $order_transactions['createtime'],
                            'shop_id' => $order_achievement['shop_id'] ?? "",
                            'order_name' => $order_achievement['name'] ?? "",
                            'financial_status' => $order_achievement['financial_status'] ?? "",
                            'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                            'tracking_number' => $order_achievement['tracking_number'] ?? "",
                            'disputetime' => strtotime($v['create_time']),
                        ];
                        Db::name('order_dispute_stripe')
                            ->where('id',$v['id'])
                            ->update($update);
                        //修改争议金额
                        $v['status'] = $this->ChangeState($v['status'],'stripe');
                        $v['dispute'] = $this->ChangeAmount($v['status'],'stripe');
                        $update_achievement = [
                            'order_id' => $order_transactions['order_id'],
                            'disputeapi_type' => $v['type'],
                            'disputeapi_status' => $v['status'] ??"暂无争议",
                            'dispute' => $v['dispute'],
                        ];
                        Db::name('order_achievement')
                            ->where('order_id',$order_transactions['order_id'])
                            ->update($update_achievement);
                        $executedCountsu++;
                    }
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //更新工单邮箱
    public function UpdateWorkOrderEmail(){
        $t1       = microtime(true);
        $count = Db::name('conversations')
            ->where('email',"=",null)
            ->count();
            echo '更新工单邮箱'.$count."条";
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('conversations')
                ->field('
                        id,
                        json
                    ')
                ->where('email',"=",null)
                ->order('id desc')
                ->limit(500)
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                $json = json_decode($v['json'],true);
                $update = [
                    'email' => $json['author']['email'] ?? "暂无",
                ];
                db::name('conversations')
                    ->where('id',$v['id'])
                    ->update($update);
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "order_dispute_airwallex-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    
    }
    
    //争议数据对应到订单Airwallex
    public function DisputeToOrdersAirwallex(){
        $t1       = microtime(true);
        $count = Db::name('order_dispute_airwallex')
            // ->where('order_id',"<=",0)
            ->where('created_at',">=",date('Y-m-d', strtotime('-4 month')))
            // ->where('created_at',"<=",date('Y-m-d', strtotime('-2 month')))
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_airwallex')
                ->field('
                        id,
                        status,
                        order_id,created_at,payment_order_id,
                        airwallex_id
                    ')
                ->where('created_at',">=",date('Y-m-d', strtotime('-4 month')))
                // ->where('created_at',"<=",date('Y-m-d', strtotime('-2 month')))
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                if(!empty($v['order_id'])){
                    //修改争议金额
                    $v['status'] = $this->ChangeState($v['status'],'airwallex');
                    $v['dispute'] = $this->ChangeAmount($v['status'],'airwallex');
                    // halt($v);
                    $update_achievement = [
                        'order_id' => $v['order_id'],
                        'disputeapi_type' => "airwallex",
                        'disputeapi_status' => $v['status'] ?? "暂无争议",
                        'dispute' => $v['dispute'],
                    ];
                    Db::name('order_achievement')
                        ->where('order_id',$v['order_id'])
                        ->update($update_achievement);

                    $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                    $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                    $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                    //更新会话
                    if(!empty($order_customer['email'])){
                        $conversations = Db::name('conversations')
                            ->where('email',$order_customer['email'])
                            ->count();
                    }else{
                        $conversations = 0;
                    }
                    $update = [
                        'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                        'conversations' => $conversations,
                        'email' => $order_customer['email'] ?? "",
                        'shop_id' => $order_achievement['shop_id'] ?? "",
                        'order_name' => $order_achievement['name'] ?? "",
                        'financial_status' => $order_achievement['financial_status'] ?? "",
                        'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                        'tracking_number' => $order_achievement['tracking_number'] ?? "",
                        'disputetime' => strtotime($v['created_at']),
                        'createtime' => $order_achievement['createtime'],
                    ];
                    Db::name('order_dispute_airwallex')
                        ->where('id',$v['id'])
                        ->update($update);
                            
                    $executedCountsu++;
                }else{
                    $order_transactions = Db::name('order_transactions')
                        ->field('
                            a.order_id,
                            a.shop_id,b.createtime,b.name
                        ')
                        ->alias('a')
                        ->join('qu_order b','b.order_id = a.order_id', 'left')
                        ->where('a.payment_id',$v['payment_order_id'])
                        ->find();
                    if(!empty($order_transactions)){
                        $order_achievement = Db::name('order_achievement')->where('order_id',$order_transactions['order_id'])->find();
                        $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                        $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                        //找到争议
                        $update = [
                            'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                            'email' => $order_customer['email'] ?? "",
                            'order_id' => $order_transactions['order_id'],
                            'createtime' => $order_transactions['createtime'],
                            'shop_id' => $order_achievement['shop_id'] ?? "",
                            'order_name' => $order_achievement['name'] ?? "",
                            'financial_status' => $order_achievement['financial_status'] ?? "",
                            'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                            'tracking_number' => $order_achievement['tracking_number'] ?? "",
                            'disputetime' => strtotime($v['created_at']),
                        ];
                        Db::name('order_dispute_airwallex')
                            ->where('id',$v['id'])
                            ->update($update);
                        //修改争议金额
                        $v['status'] = $this->ChangeState($v['status'],'airwallex');
                        $v['dispute'] = $this->ChangeAmount($v['status'],'airwallex');
                        $update_achievement = [
                            'order_id' => $order_transactions['order_id'],
                            'disputeapi_type' => "airwallex",
                            'disputeapi_status' => $v['status'] ??"暂无争议",
                            'dispute' => $v['dispute'],
                        ];
                        Db::name('order_achievement')
                            ->where('order_id',$order_transactions['order_id'])
                            ->update($update_achievement);
                        $executedCountsu++;
                    }
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "order_dispute_airwallex-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    
    }
    //争议数据对应到订单Airwallex
    public function DisputeToOrdersAirwallexShop(){
        $t1       = microtime(true);
        $count = Db::name('order_dispute_airwallex')
            ->where('shop_id',"<=",0)
            ->where('order_id',">",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_airwallex')
                ->field('
                        id,
                        status,
                        order_id,
                        airwallex_id
                    ')
                ->where('order_id',">",0)
                ->where('shop_id',"<=",0)
                ->order('id asc')
                ->limit(500)
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                if(!empty($v['order_id'])){
                    $order = Db::name('order')->field('shop_id')->where('order_id',$v['order_id'])->find();
                    $shop_id = $order['shop_id'] ?? 0;
                    if($shop_id >0){
                        $update = [
                            'shop_id' => $shop_id,
                        ];
                        db::name('order_dispute_airwallex')
                            ->where('id',$v['id'])
                            ->update($update);
                    }
                    $executedCountsu++;
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "order_dispute_airwallex-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    
    }
    //争议数据对应到订单Paypal
    public function DisputeToOrdersPaypal(){
        // $order_dispute = Db::name('order_dispute_paypal_copy1')->select()->toarray();
        // $order_disputes = [];
        // foreach($order_dispute as &$v){
        //     echo $v['id']."完成".PHP_EOL;
        //     $paypal = Db::name('order_dispute_paypal')->where('dispute_id',$v['dispute_id'])->find();
        //     if(!empty($paypal)){
        //         unset($v['id']);
        //         $order_disputes[] = $v;
        //     }
        // }
        // // halt($order_disputes);
        // if(!empty($order_disputes)){
        //     Db::name('order_dispute_paypal')->insertAll($order_disputes);
        // }
        $t1       = microtime(true);
        $count = Db::name('order_dispute_paypal')
            ->where('create_time',">=",date('Y-m-d', strtotime('-3 month')))
            // ->where('order_id',"<=",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_paypal')
                ->field('
                        id,
                        api_type,
                        type,
                        status,
                        order_id,create_time,
                        seller_transaction_id
                    ')
                ->where('create_time',">=",date('Y-m-d', strtotime('-3 month')))
                // ->where('order_id',"<=",0)
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                if(!empty($v['order_id'])){
                    //修改争议金额
                    $v['status'] = $this->ChangeState($v['status'],'paypal');
                    $v['dispute'] = $this->ChangeAmount($v['status'],'paypal');
                    $update_achievement = [
                        'order_id' => $v['order_id'],
                        'disputeapi_type' => $v['type'],
                        'disputeapi_status' => $v['status'] ?? "暂无争议",
                        'dispute' => $v['dispute'],
                    ];
                    Db::name('order_achievement')
                        ->where('order_id',$v['order_id'])
                        ->update($update_achievement);

                    $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                    $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                    $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                    //更新会话
                    if(!empty($order_customer['email'])){
                        $conversations = Db::name('conversations')
                            ->where('email',$order_customer['email'])
                            ->count();
                    }else{
                        $conversations = 0;
                    }
                    $update = [
                        'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                        'conversations' => $conversations,
                        'email' => $order_customer['email'] ?? "",
                        'shop_id' => $order_achievement['shop_id'] ?? "",
                        'order_name' => $order_achievement['name'] ?? "",
                        'financial_status' => $order_achievement['financial_status'] ?? "",
                        'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                        'tracking_number' => $order_achievement['tracking_number'] ?? "",
                        'disputetime' => strtotime($v['create_time']),
                    ];
                    Db::name('order_dispute_paypal')
                        ->where('id',$v['id'])
                        ->update($update);

                    $executedCountsu++;
                }else{
                    $order_transactions = Db::name('order_transactions')
                        ->field('
                            a.order_id,
                            a.shop_id,b.createtime,b.name
                        ')
                        ->alias('a')
                        ->join('qu_order b','b.order_id = a.order_id', 'left')
                        ->where('a.authorization',$v['seller_transaction_id'])
                        ->find();
                    if(!empty($order_transactions)){
                        $order_achievement = Db::name('order_achievement')->where('order_id',$order_transactions['order_id'])->find();
                        $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                        $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                        //找到争议
                        $update = [
                            'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                            'email' => $order_customer['email'] ?? "",
                            'order_id' => $order_transactions['order_id'],
                            'createtime' => $order_transactions['createtime'],
                            'shop_id' => $order_achievement['shop_id'] ?? "",
                            'order_name' => $order_achievement['name'] ?? "",
                            'financial_status' => $order_achievement['financial_status'] ?? "",
                            'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                            'tracking_number' => $order_achievement['tracking_number'] ?? "",
                            'disputetime' => strtotime($v['create_time']),
                        ];
                        Db::name('order_dispute_paypal')
                            ->where('id',$v['id'])
                            ->update($update);
                        //修改争议金额
                        $v['status'] = $this->ChangeState($v['status'],'paypal');
                        $v['dispute'] = $this->ChangeAmount($v['status'],'paypal');
                        $update_achievement = [
                            'order_id' => $order_transactions['order_id'],
                            'disputeapi_type' => $v['type'],
                            'disputeapi_status' => $v['status'] ??"暂无争议",
                            'dispute' => $v['dispute'],
                        ];
                        Db::name('order_achievement')
                            ->where('order_id',$order_transactions['order_id'])
                            ->update($update_achievement);
                        $executedCountsu++;
                    }
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function AfterpayHistory(){
        $dispute_afterpay = Config('Logisticskey.dispute_afterpay');
        foreach ($dispute_afterpay as $k=>$v) {
            $this->AfterpayHistorys($v);
        }
    }

    public function AfterpayHistorys($config){
        $count = $config['count'] ?? 4500;
        $pageSize = 10;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        
        for ($i = 0; $i <= $page; $i++){
            $offset = $pageSize*$i;
            $api_type    = $config['api_type'] ?? "";
            $url = $config['path']."".$config['disputes'];
            $url = $url . '?offset='.$offset.'&limit=10';
            echo "下一页标识-".$offset. PHP_EOL;
            $data = HttpUtil::getUrl($url,$config);
            echo "总共-".$data['total']. PHP_EOL;
            if ($data) {
                if (!empty($data['error'])) {
                    echo $data['error'];die;
                    // $arr_error['type'] = 'afterpay_error';
                    // $arr_error['api_type'] = $api_type;
                    // $arr_error['json'] = json_encode($data, true);
                    // Db::name('order_dispute_afterpay')->insert($arr_error);
                }
                if (isset($data['data']) && !empty($data['data']) && is_array($data['data'])) {
                    $orders = $data['data'];
                    date_default_timezone_set('Asia/Shanghai');
                    foreach ($orders as  $order) {
                        $dispute_info = Db::name('order_dispute_afterpay')->where('dispute_id',$order['id'])->find();
                        $arr = [];
                        $arr['updatedAt'] = $order['updatedAt'] ?? 0;
                        if ($dispute_info) {
                            $dispute_info['updatedAt'] = $dispute_info['updatedAt'] ?? 0;
                            $arr['status'] = $order['status'] ?? "";
                            if($order['open'] == false){
                                $arr['revoke_status'] = 1;
                            }
                            $arr['json'] = json_encode($order, true);
                            if($dispute_info['updatedAt'] > strtotime($arr['updatedAt'])){
                                Db::name('order_dispute_afterpay')->where(['dispute_id' => $order['id']])->update($arr);
                                $executedCount++;
                            }
                        } else {
                            $arr['type'] = 'afterpay';
                            $arr['createdAt'] = $order['createdAt'] ?? 0;
                            $arr['order'] = $order['order'] ?? "";
                            $arr['status'] = $order['status'] ?? "";
                            if($order['open'] == false){
                                $arr['revoke_status'] = 1;
                            }
                            $arr['amount'] = $order['amount'] ?? "";
                            $arr['currency'] = $order['currency'] ?? "";
                            $arr['reason'] = $order['reason'] ?? "";
                            $arr['open'] = $order['open'] ?? "";
                            $arr['responseDueBy'] = $order['responseDueBy'] ?? "";
                            $arr['openingNote'] = $order['openingNote'] ?? "";
                            $arr['merchantOrderId'] = $order['merchantOrderId'] ?? "";
                            $arr['transactionDate'] = $order['transactionDate'] ?? "";
                            $arr['api_type'] = $api_type;
                            
                            $arr['json'] = json_encode($order, true);
                            $arr['dispute_id'] = $order['id'];
                            Db::name('order_dispute_afterpay')->insert($arr);
                            $executedCountsu++;
                        }
                        $num = $count - $executedCount;
                        echo PHP_EOL . "总计:" . $count . '条' . '-----' . "修改:" . $executedCount . '-----' . '剩余:' . $num . '条,新增'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
                    }
                }
            }
        }
        echo "完成". PHP_EOL;
    }

    //临时打元子段--dispute标签
    public function DisputeSubSegment(){
        $count = Db::name('order_achievement')
            ->where('disputeapi_type',"<>",'')
            // ->where('disputeapi_status',"<>",'其他')
            ->where('metafields_status',"=",0)
            ->count();
            // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;
        
        for ($i = 0; $i <= $count; $i++){
            $shop_info = Db::name('order_achievement')
                ->field('
                    a.id,
                    a.order_id,
                    a.shop_id,
                    a.tags,
                    a.disputeapi_type,
                    a.disputeapi_status,
                    b.myshopify_domain,
                    b.app_key,
                    b.app_secret
                ')
                ->alias('a')
                ->join('qu_shops b','b.id = a.shop_id', 'left')
                // ->where('order_id',$order_id)
                ->where('disputeapi_type',"<>",'')
                // ->where('disputeapi_status',"<>",'其他')
                ->where('metafields_status',"=",0)
                ->find();
            if (empty($shop_info)) {
                echo "该订单暂无争议信息" . PHP_EOL;
                continue;
            }
            $order_id = $shop_info['order_id'];
            // 开始打标签
            $url = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id.".json";
            $tags = !empty($shop_info['tags']) ? $shop_info['tags'] . ",dispute" : "dispute";
            $data = [
                'order' => [
                    'id' => $order_id,
                    'tags' => $tags,
                ],
            ];
            // halt($url);
            HttpUtil::PutUrl($url, $data, $shop_info);
            //开始打元子段
            $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$shop_info['order_id']."/metafields.json";   

            $post = array();
            $post['metafield']['namespace'] = 'custom';
            $post['metafield']['key'] =  '_dispute';

            if($shop_info['disputeapi_status'] == "其他"){
                $shop_info['disputeapi_status'] = "待处理";
            }
            $post['metafield']['value'] = [
                '0' => $shop_info['disputeapi_status'],
            ];
            $post['metafield']['value'] = json_encode($post['metafield']['value'], true);
            $post['metafield']['type'] = 'list.single_line_text_field';
            // halt($post);
            $return = HttpUtil::PostUrl($url,$post, $shop_info);
            $return = json_decode($return, true);
            if(!empty($return['errors']) || !empty($return['error'])){
                $update['metafields_status'] = 2;
                Db::name('order_achievement')
                    ->where('id',$shop_info['id'])
                    ->update($update);
            }else{
                $update['metafields_status'] = 1;
                Db::name('order_achievement')
                    ->where('id',$shop_info['id'])
                    ->update($update);
                $executedCountsu++;
            }
            $executedCount++;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '成功'.$executedCountsu.'条，当前订单id:'.$order_id.',第' .$i.'条' . PHP_EOL;
        }
        echo "完成". PHP_EOL;
    }

    public function AfterpayPaymentsHistory(){
        $date = '2025-01-01';
        $datelast = '2025-01-14';
        // $date = date('Y-m-d', time() - 3600 * 24 * 10);
        // $datelast = date('Y-m-d', time());
        $count = 7000;

        $pageSize = 10;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;

        $dispute_afterpay = Config('Logisticskey.dispute_afterpay');
        $config = $dispute_afterpay[0];
        for ($i = 0; $i <= $page; $i++){
            $offset = $pageSize*$i;
            $api_type    = $config['api_type'];
            $url = $config['path']."".$config['payments'];
            $url = $url . '?offset='.$offset.'&limit=10&fromCreatedDate='.$date."&toCreatedDate=".$datelast;
            echo $offset. PHP_EOL;
            $data = HttpUtil::getUrl($url,$config);
            // halt($data['totalResults']);
            if ($data) {
                if (isset($data['results']) && !empty($data['results']) && is_array($data['results'])) {
                    $orders = $data['results'];
                    date_default_timezone_set('Asia/Shanghai');
                    foreach ($orders as $order) {
                        // halt($order);
                        $arr = [];
                        $arr['api_type'] = $api_type;
                        $arr['type'] = 'afterpay';
                        $arr['dispute_id'] = $order['id'] ?? "";
                        $arr['created'] = $order['created'] ?? "";
                        $arr['phoneNumber'] = $order['orderDetails']['consumer']['phoneNumber'] ?? "";
                        $arr['givenNames'] = $order['orderDetails']['consumer']['givenNames'] ?? "";
                        $arr['surname'] = $order['orderDetails']['consumer']['surname'] ?? "";
                        $arr['email'] = $order['orderDetails']['consumer']['email'] ?? "";
                        $executedCount++;
                        $dispute_apconsumer = Db::name('order_dispute_apconsumer')->where('dispute_id',$order['id'])->find();
                        if(empty($dispute_apconsumer)){
                            echo "总共".$data['totalResults'].",当前".$executedCount.",新增" . PHP_EOL;
                            Db::name('order_dispute_apconsumer')->insert($arr);
                        }else{
                            echo "总共".$data['totalResults'].",当前".$executedCount.",已存在" . PHP_EOL;
                        }
                    }
                }
            }
            echo "api完成";
        }
        echo "完成". PHP_EOL;;
    }

    public function Afterpayorder(){
        $count = Db::name('order_dispute_apconsumer')
            ->where('update',0)
            ->count();
            
        echo "临时打元子段".$count . PHP_EOL;
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        
        for ($i = 1; $i <= $page; $i++){
            $apconsumer = Db::name('order_dispute_apconsumer')
                ->where('update',0)
                ->limit($pageSize)
                ->select()->toarray();
            foreach ($apconsumer as $v){
                $executedCount++;
                if(!empty($v['phoneNumber'])){
                    $customer = DB::name('order_customer')
                        ->where('shop_id',17)
                        ->where('phone',$v['phoneNumber'])
                        ->find();
                    if($customer){
                        $executedCountsu++;
                        $update = [];
                        $update['order_id'] = $customer['order_id'];
                        $update['update'] = 1;
                        Db::name('order_dispute_apconsumer')
                            ->where('id',$v['id'])
                            ->update($update);
                        echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' .$customer['order_id']. PHP_EOL;
                        continue;
                    }
                }
                if(!empty($v['givenNames']) && !empty($v['surname'])){
                    $customer = DB::name('order_customer')
                        ->where('shop_id',17)
                        ->where('first_name',$v['givenNames'])
                        ->where('last_name',$v['surname'])
                        ->find();
                    if($customer){
                        $executedCountsu++;
                        $update = [];
                        $update['order_id'] = $customer['order_id'];
                        $update['update'] = 1;
                        Db::name('order_dispute_apconsumer')
                            ->where('id',$v['id'])
                            ->update($update);
                        echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' .$customer['order_id']. PHP_EOL;
                        continue;
                    }
                }
                if(!empty($v['email'])){
                    $customer = DB::name('order_customer')
                        ->where('shop_id',17)
                        ->where('email',$v['email'])
                        ->find();
                    if($customer){
                        $executedCountsu++;
                        $update = [];
                        $update['order_id'] = $customer['order_id'];
                        $update['update'] = 1;
                        Db::name('order_dispute_apconsumer')
                            ->where('id',$v['id'])
                            ->update($update);
                        echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' .$customer['order_id']. PHP_EOL;
                        continue;
                    }
                }
                $update['update'] = 2;
                Db::name('order_dispute_apconsumer')
                    ->where('id',$v['id'])
                    ->update($update);
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
            }
        }
    }
    //争议数据对应到订单afterpay
    public function DisputeToOrdersAfterpay(){
        //去重Afterpay
        // $count = Db::name('order_dispute_afterpay')
        //     ->where('shop_id',"<>",0)
        //     ->group('order_id')
        //     ->having('COUNT(*) > 1')
        //     ->count();
        // halt($count);
        // echo PHP_EOL . "去重Afterpay-开始操作" . PHP_EOL;
        // if(!empty($count)){
        //     $duplicates = Db::name('order_dispute_afterpay')
        //         ->field('order_id, COUNT(*) as num_duplicates')
        //         ->where('shop_id',"<>",0)
        //         ->group('order_id')
        //         ->having('COUNT(*) > 1')
        //         ->select()
        //         ->toArray();
        //     $executedCount = 0;
        //     foreach ($duplicates as $duplicate) {
        //         $keepIds = Db::name('order_dispute_afterpay')
        //             ->field('id')
        //             ->where('order_id', $duplicate['order_id'])
        //             ->order('updatedAt desc')
        //             ->find();
        //         $keepId = $keepIds['id'] ?? 0;
        //         // 删除其他所有ID的记录
        //         Db::name('order_dispute_afterpay')
        //             ->where('order_id', $duplicate['order_id'])
        //             ->where('id', '<>', $keepId) // 排除要保留的记录
        //             ->delete();
        //         $executedCount++;
        //         $num = $count - $executedCount;
        //         echo PHP_EOL . "去重Afterpay总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        //     }
        // }

        $t1       = microtime(true);
        $count = Db::name('order_dispute_afterpay')
            ->where('createdAt',">=",strtotime('-3 month'))
            // ->where('order_id',"<=",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_afterpay')
                ->field('
                        id,
                        api_type,
                        type,
                        order_id,
                        status,createdAt,
                        merchantOrderId
                    ')
                    ->where('createdAt',">=",strtotime('-3 month'))
                    // ->where('order_id',"<=",0)
                    ->order('id desc')
                    ->paginate([  
                        'list_rows' => $pageSize,
                        'page' => $i,
                    ])->toarray();
            
            foreach ($list['data'] as $v){
                if(!empty($v['order_id'])){
                    //修改争议金额
                    $v['status'] = $this->ChangeState($v['status'],'afterpay');
                    $v['dispute'] = $this->ChangeAmount($v['status'],'afterpay');
                    $update_achievement = [
                        'order_id' => $v['order_id'],
                        'disputeapi_type' => $v['type'],
                        'disputeapi_status' => $v['status'] ?? "暂无争议",
                        'dispute' => $v['dispute'],
                    ];
                    Db::name('order_achievement')
                        ->where('order_id',$v['order_id'])
                        ->update($update_achievement);

                    $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                    $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                    $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                    //更新会话
                    if(!empty($order_customer['email'])){
                        $conversations = Db::name('conversations')
                            ->where('email',$order_customer['email'])
                            ->count();
                    }else{
                        $conversations = 0;
                    }
                    $update = [
                        'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                        'conversations' => $conversations,
                        'email' => $order_customer['email'] ?? "",
                        'shop_id' => $order_achievement['shop_id'] ?? "",
                        'order_name' => $order_achievement['name'] ?? "",
                        'financial_status' => $order_achievement['financial_status'] ?? "",
                        'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                        'tracking_number' => $order_achievement['tracking_number'] ?? "",
                        'disputetime' => $v['createdAt'],
                    ];
                    Db::name('order_dispute_afterpay')
                        ->where('id',$v['id'])
                        ->update($update);

                }else{
                    $order_transactions = Db::name('order_transactions')
                        ->field('
                            a.order_id,
                            a.shop_id,b.createtime,b.name
                        ')
                        ->alias('a')
                        ->join('qu_order b','b.order_id = a.order_id', 'left')
                        ->where('a.payment_id',$v['merchantOrderId'])
                        ->find();
                    if(!empty($order_transactions)){
                        $order_achievement = Db::name('order_achievement')->where('order_id',$order_transactions['order_id'])->find();
                        $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                        $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                        //找到争议
                        $update = [
                            'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                            'email' => $order_customer['email'] ?? "",
                            'order_id' => $order_transactions['order_id'],
                            'createtime' => $order_transactions['createtime'],
                            'shop_id' => $order_achievement['shop_id'] ?? "",
                            'order_name' => $order_achievement['name'] ?? "",
                            'financial_status' => $order_achievement['financial_status'] ?? "",
                            'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                            'tracking_number' => $order_achievement['tracking_number'] ?? "",
                            'disputetime' => $v['createdAt'],
                        ];
                        Db::name('order_dispute_afterpay')
                            ->where('id',$v['id'])
                            ->update($update);
                        //修改争议金额
                        $v['status'] = $this->ChangeState($v['status'],'afterpay');
                        $v['dispute'] = $this->ChangeAmount($v['status'],'afterpay');
                        $update_achievement = [
                            'order_id' => $order_transactions['order_id'],
                            'disputeapi_type' => $v['type'],
                            'disputeapi_status' => $v['status'] ??"暂无争议",
                            'dispute' => $v['dispute'],
                        ];
                        Db::name('order_achievement')
                            ->where('order_id',$order_transactions['order_id'])
                            ->update($update_achievement);
                        $executedCountsu++;
                    }
                }   
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //QueryOrderTransactionApi
    public function QueryOrderTransactionApi(){
        $t1       = microtime(true);

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();

        $start_time = '1735660800';//临时
        $end_time = time();//临时

        // $update_dispute['dispute_status'] = 0;
        // $updates = Db::name('order')
        //     ->where('createtime',">=",$start_time)
        //     ->where('createtime',"<=",$end_time)
        //     // ->where('shop_id',"in",[17,21,18])
        //     ->where('shop_id',17)
        //     ->update($update_dispute);
        // halt($updates);
        //统计
        // halt($start_time);

        // $end_time = time();
        $count = Db::name('order')
            ->where('createtime',">=",$start_time)
            ->where('createtime',"<=",$end_time)
            ->where('dispute_status',0)
            // ->where('shop_id',"in",[17,21,18])
            ->where('shop_id',17)
            ->count();
            // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order')
                ->field('shop_id,order_id,createtime')
                ->where('createtime',">=",$start_time)
                ->where('createtime',"<=",$end_time)
                ->where('dispute_status',0)
                // ->where('shop_id',"in",[17,21,18])
                ->where('shop_id',17)
                ->order('createtime asc')
                ->limit(500)
                ->select()
                ->toArray();
            $shop_id        = 17;
            $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
            foreach ($list as $v){
                $return = $this->QueryOrderTransactionApiedit($v,$shop_info);
                if($return){
                    $executedCountsu++;
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function QueryOrderTransactionApiedit($order,$shop_info)
    {
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version . "/orders/".$order['order_id']."/transactions.json";
        $return = HttpUtil::getUrl($url, $shop_info);
        if(!empty($return)){
            // Db::name('order_transactions')->where('order_id',$order['order_id'])->delete();
            $inserts = [];
            $transactions = $return['transactions'];
            foreach ($transactions as $k=>$vt) {
                $arr_transactions = [];
                $arr_transactions['order_id'] = $order['order_id'];
                $arr_transactions['shop_id'] = $order['shop_id'];
                $arr_transactions['transactions_id'] = $vt['id'];
                $arr_transactions['status'] = $vt['status'] ?? "";
                $arr_transactions['gateway'] = $vt['gateway'] ?? "";
                $arr_transactions['message'] = $vt['message'] ?? "";
                $arr_transactions['authorization'] = $vt['authorization'] ?? "";
                $arr_transactions['amount'] = $vt['amount'] ?? "";
                $arr_transactions['currency'] = $vt['currency'] ?? "";
                $arr_transactions['payment_id'] = $vt['payment_id'] ?? "";
                $arr_transactions['kind'] = $vt['kind'] ?? "";
                $arr_transactions['created_at'] = $vt['created_at'] ?? "";
                $arr_transactions['parent_txn_id'] = 0;
                if(!empty($vt['receipt'])){
                    $arr_transactions['parent_txn_id'] = $vt['receipt']['parent_txn_id'] ?? 0;
                }
                $inserts[] = $arr_transactions;
                Db::name('order_transactions')->where('transactions_id',$arr_transactions['transactions_id'])->delete();
            }
            Db::name('order_transactions')->insertAll($inserts);
        }
        $update['dispute_status'] = 1;
        $order = Db::name('order')
            ->where('order_id',$order['order_id'])
            ->update($update);
        return true; 
    }

    //临时打元子段
    public function TemporaryYuanSubSegment()
    {
        $count = Db::name('order_dispute_apconsumer')
            ->where('uploadstatus',0)
            ->count();
            
        echo "临时打元子段".$count . PHP_EOL;
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        
        $shop_info = Db::name('shops')->where('id',17)->find();
        for ($i = 1; $i <= $page; $i++){
            $apconsumer = Db::name('order_dispute_apconsumer')
                ->where('uploadstatus',0)
                ->limit($pageSize)
                ->select()->toarray();
            foreach ($apconsumer as $v){
                $executedCount++;
                if(!empty($v['phoneNumber'])){
                    $customer = DB::name('order_customer')
                        ->where('shop_id',17)
                        ->where('phone',$v['phoneNumber'])
                        ->find();
                    if($customer){
                        $executedCountsu++;
                        $this->add_metafield_afterpay($customer['order_id'],$shop_info,$v);
                        echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' .$customer['order_id']. PHP_EOL;
                        continue;
                    }
                }
                if(!empty($v['givenNames']) && !empty($v['surname'])){
                    $customer = DB::name('order_customer')
                        ->where('shop_id',17)
                        ->where('first_name',$v['givenNames'])
                        ->where('last_name',$v['surname'])
                        ->find();
                    if($customer){
                        $executedCountsu++;
                        $this->add_metafield_afterpay($customer['order_id'],$shop_info,$v);
                        echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' .$customer['order_id']. PHP_EOL;
                        continue;
                    }
                }
                if(!empty($v['email'])){
                    $customer = DB::name('order_customer')
                        ->where('shop_id',17)
                        ->where('email',$v['email'])
                        ->find();
                    if($customer){
                        $executedCountsu++;
                        $this->add_metafield_afterpay($customer['order_id'],$shop_info,$v);
                        echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' .$customer['order_id']. PHP_EOL;
                        continue;
                    }
                }
                $update['uploadstatus'] = 2;
                Db::name('order_dispute_apconsumer')
                    ->where('id',$v['id'])
                    ->update($update);
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
            }
        }
    }

    

    //修改配送状态
    public function ModifyDeliveryStatus()
    {
        // $shipment_status_arr = Db::name('order_achievement')
        //     ->field('shipment_status,count(id) as count')
        //     ->where('createtime','>=',strtotime('-4 month'))
        //     ->where('fulfillment_status',"fulfilled")
        //     ->group('shipment_status')
        //     ->select()->toarray();
        // halt($shipment_status_arr);

        $count = Db::name('order_achievement')
            ->where('createtime','>=',strtotime('-4 month'))
            ->where('fulfillment_status',"fulfilled")
            ->where('shipment_status',"in_transit")
            ->count();
        echo PHP_EOL . "总计:" . $count . '条' . PHP_EOL;
        // halt($count);
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;

        for ($i = 0; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('id,shop_id,order_id,tracking_number,shipment_status')
                ->where('createtime','>=',strtotime('-4 month'))
                ->where('fulfillment_status',"fulfilled")
                ->where('shipment_status',"in_transit")
                ->order('createtime desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
                foreach ($list['data'] as $k => $v) {
                    sleep(1);
                    // halt($v);
                    $executedCount++;
                    $number = $v['tracking_number'];
                    if (strpos($number, '4PX') !== false) { 
                        $params = [];
                        $params['track_number'] = $v['tracking_number'];
                        try {
                            $res    =  (new CheckLogic())->track_4px($params);
                            // halt($res);
                            $trackingContent = $res['data'];
                            $trackDetails = $trackingContent['trackingList'] ?? "";
                            $businessStatus = '';
                            $occurDatetime = '';
                            if (!empty($trackDetails)) {
                                foreach ($trackDetails as $key => $value) {
                                    if(empty($businessStatus)){
                                        $businessStatus = $value['trackingContent'];
                                        $occurDatetime = $value['occurDatetime'];
                                    }else{
                                        break;
                                    }
                                }
                            }
                        } catch (\Throwable $e) {
                        }
                    }
                    if (strpos($number, 'DYY') !== false) { 
                        // try {
                            $result = $this->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$number);
                            $res = json_decode($result['result'], true);
                            $trackingContent = $res[0]['data'][0] ?? "";
                            $businessStatus = $trackingContent['trackContent'] ?? "";
                        // } catch (\Throwable $e) {
                        // }
                    }
                    // halt($businessStatus);
                    if(empty($businessStatus)){
                        halt($res);
                    }
                    echo $number. ':'.$businessStatus;
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
                }
        }
    }

    //4px系统API
    public function pxSystemApis()
    {
        // $tracking_number = '4PX3001832467495CN';
        $tracking_number = '4PX';
        $count = Db::name('order_achievement')
            ->where('createtime','>=',strtotime('-4 month'))
            ->where('tracking_number',"like","%{$tracking_number}%")
            ->where('fulfillment_status',"fulfilled")
            ->count();
        echo PHP_EOL . "总计:" . $count . '条' . PHP_EOL;
        // halt($count);
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;

        for ($i = 0; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('id,order_id,tracking_number,createtime,shop_id')
                ->where('createtime','>=',strtotime('-4 month'))
                ->where('tracking_number',"like","%{$tracking_number}%")
                ->where('fulfillment_status',"fulfilled")
                ->order('createtime desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
                foreach ($list['data'] as $k => $v) {
                    $executedCount++;

                    $number = $v['tracking_number'];
                    $params = [];
                    $params['track_number'] = $v['tracking_number'];
                    // $params['track_number']  = "4PX3001821763393CN";

                    // try
                    try {
                        $res    =  (new CheckLogic())->track_4px($params);
                    } catch (\Throwable $e) {
                        echo "修改失败". PHP_EOL;  
                        continue;
                    }
                    // halt($res);
                    $trackingContent = $res['data'];
                    $business_channeltransfercode = $trackingContent['serverNum'] ?? "";
                    $trackDetails = $trackingContent['trackingList'] ?? "";
                    $businessStatus = '';
                    $occurDatetime = '';
                    if (!empty($trackDetails)) {
                        foreach ($trackDetails as $key => $value) {
                            if(empty($businessStatus)){
                                $businessStatus = $value['trackingContent'];
                                $occurDatetime = $value['occurDatetime'];
                            }else{
                                break;
                            }
                        }
                        $trackDetails = json_encode($trackDetails,true);
                    }
                    $insert = [
                        'order_id' => $v['order_id'],
                        'shop_id' => $v['shop_id'],
                        'waybill_no_new' => $business_channeltransfercode,
                        'track_number' => $number,
                        'provider_name' => "4PX",
                        'latest_status' => $businessStatus ?? "",
                        'latest_sub_status' => $businessStatus ?? "",
                        'create_time' => $occurDatetime ?? "",
                        'provider_country' => $trackingContent['destinationCountry'] ?? "",
                        'tracking_list' => $trackDetails,
                    ];
                    // halt($insert);
                    if (Db::name('order_trackfree')->where('provider_name', "4PX")->where('track_number', $number)->find()) {
                        // $insert['update_time'] = $occurDatetime ?? "";
                        // Db::name('order_trackfree')->where('provider_name', "4PX")->where('track_number', $number)->update($insert);
                    }else{
                        Db::name('order_trackfree')->insert($insert);
                        $executedCountsu++;
                    }

                    // if (!empty($trackingList)) {
                        // foreach ($trackingList as $kt => $vt) {
                        //     if (strpos($vt['trackingContent'], '退') !== false) {
                        //         $trackingContent = $vt['trackingContent'];
                        //         break;
                        //     }
                        //     if (strpos($vt['trackingContent'], 'Return') !== false) {
                        //         $trackingContent = $vt['trackingContent'];
                        //         break;
                        //     }
                        // }
                    // }
                    // if (!empty($trackingContent)) {
                    //     $insert = [
                    //         'order_id' => $v['order_id'],
                    //         'createtime' => $v['createtime'],
                    //         'waybill_no' => $number,
                    //         'waybill_no_new' => $business_channeltransfercode,
                    //         'trackingContent' => $trackingContent,
                    //     ];
                    //     Db::name('yuan_subsegment_4px_error')->insert($insert);
                    //     $executedCountsu++;
                    // }

                    // if (!empty($business_channeltransfercode)) {
                    //     $insert = [
                    //         'waybill_no' => $number,
                    //         'waybill_no_new' => $business_channeltransfercode,
                    //     ];
                    //     Db::name('yuan_subsegment_4px')->insert($insert);
                    //     $executedCountsu++;
                    // }
                    
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
                }
        }
    }
    //华磊系统API
    public function HualeiSystemApis()
    {
        // $tracking_number = 'DYY253329282XB';
        $tracking_number = 'DYY';
        $count = Db::name('order_achievement')
            ->where('createtime','>=',strtotime('-4 month'))
            ->where('tracking_number',"like","%{$tracking_number}%")
            ->where('fulfillment_status',"fulfilled")
            ->count();
        echo PHP_EOL . "总计:" . $count . '条' . PHP_EOL;
        // halt($count);
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;

        for ($i = 0; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('id,order_id,tracking_number,shop_id')
                ->where('createtime','>=',strtotime('-4 month'))
                ->where('tracking_number',"like","%{$tracking_number}%")
                ->where('fulfillment_status',"fulfilled")
                ->order('createtime desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
                foreach ($list['data'] as $k => $v) {
                    $executedCount++;

                    $number = $v['tracking_number'];
                    $result = $this->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$number);
                    $resultData = json_decode($result['result'], true);
                    // halt($resultData);
                    
                    $business_channeltransfercode = $resultData[0]['data'][0]['business_channeltransfercode'] ?? "";
                    $trackingContent = $resultData[0]['data'][0] ?? "";
                    if (!empty($trackingContent)) {
                        // if($business_channeltransfercode == '签收'){
                        //     echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
                        //     continue;
                        // }
                        // if(empty($business_channeltransfercode)){
                        //     echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
                        //     continue;
                        // }
                        $trackDetails = $trackingContent['trackDetails'] ?? "";
                        if (!empty($trackDetails)) {
                            $trackDetails = json_encode($trackDetails,true);
                        }
                        $insert = [
                            'order_id' => $v['order_id'],
                            'shop_id' => $v['shop_id'],
                            'waybill_no_new' => $business_channeltransfercode,
                            'track_number' => $number,
                            'provider_name' => "DYY",
                            'latest_status' => $trackingContent['businessStatus'] ?? "",
                            'latest_sub_status' => $trackingContent['businessStatus'] ?? "",
                            'create_time' => $trackingContent['trackDate'] ?? "",
                            'provider_country' => $trackingContent['consigneeCountry'] ?? "",
                            'tracking_list' => $trackDetails,
                        ];
                        if (Db::name('order_trackfree')->where('provider_name', "DYY")->where('track_number', $number)->find()) {
                            // $insert['update_time'] = $trackingContent['trackDate'] ?? "";
                            // Db::name('order_trackfree')->where('provider_name', "DYY")->where('track_number', $number)->update($insert);
                        }else{
                            $executedCountsu++;
                            Db::name('order_trackfree')->insert($insert);
                        }
                    }
                    
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
                }
        }
    }
    //华磊系统API
    public function HualeiSystemApi($params = [])
    {
        $number = $params['number'] ?? "";
        //渠道列表
        // $rs = $this->curlRequest('http://43.139.12.243:8082/getProductList.htm', "username=szzt&password=123456");
        // halt($rs);
        //身份认证
        // $rs = $this->curlRequest('http://43.139.12.243:8082/selectAuth.htm', "username=szzt&password=123456");
        // $reData = json_decode(str_replace("'", "\"", $rs['result']));
        // $customer_id = $reData->customer_id;
        // $customer_userid = $reData->customer_userid;
        // halt($customer_userid);
        // $data = Array(
        //     'buyerid' => '',
        //     'consignee_address' => 'Blumenstraße',
        //     'consignee_city' => 'Kulmain',
        //     'consignee_mobile' => '',
        //     'consignee_name' => 'Johann Schindler',
        //     'trade_type' => 'ZYXT',
        //     'consignee_postcode' => '95508',
        //     'consignee_state' => 'SHANG HAI',
        //     'consignee_telephone' => '',
        //     'country' => 'DE',
        //     'customer_id' => $customer_id,
        //     'customer_userid' => $customer_userid,
        //     'orderInvoiceParam' => Array(
        //             '0' => Array
        //             (
        //                     'invoice_amount' => 3.5,
        //                     'invoice_pcs' => 1,
        //                     'invoice_title' => 'candle lights',
        //                     'invoice_weight' => 0.571,
        //                     'item_id' => '',
        //                     'item_transactionid' => '',
        //                     'sku' => '测试新增订单',
        //                     'sku_code' => 'HL101',
        //             ),
        //             '1' => Array
        //             (
        //                     'invoice_amount' => 3.5,
        //                     'invoice_pcs' => 1,
        //                     'invoice_title' => 'candle lights',
        //                     'invoice_weight' => 0.534,
        //                     'item_id' => '',
        //                     'item_transactionid' =>'',
        //                     'sku' => '测试新增订单',
        //                     'sku_code' => 'HL103',
        //             ),
        //     ),
        //     'order_customerinvoicecode' => 'SO781507140104',
        //     'product_id' => "2601",
        //     'weight' => 1.105,
        //     'product_imagepath' => '',
        // );
        // halt($data);
        // $result = $this->curlRequest('http://43.139.12.243:8082/createOrderApi.htm', "param=" . json_encode($data));
        // halt($result);
        //测试添加订单结束
        
        // 轨迹查询
        $result = $this->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$number);
        $resultData = json_decode($result['result'], true);
        $business_channeltransfercode = $resultData[0]['data'][0]['business_channeltransfercode'] ?? "";
        if (!empty($business_channeltransfercode)) {
            $url = 'https://www.uniuni.com/tracking/#tracking-detail?no='.$business_channeltransfercode;
            echo "链接地址：".$url;
        }else{
            echo "没有找到转单号";
        }
        //获取跟踪号
        $result = $this->curlRequest('http://43.139.12.243:8082/getOrderTrackingNumber.htm', "documentCode=92612903396157000106075280");
        $resultData = json_decode($result['result'], true);
        halt($resultData);
        $order_achievement = [
            'shop_id' => 17,
            'order_id' => 123,
            'waybill_no_new' => "123",
        ];
        $shop_info = Db::name('shops')->where('id',$order_achievement['shop_id'])->find();
        $this->add_metafield_transfer($order_achievement['order_id'],$shop_info,$order_achievement['waybill_no_new']);
    }

    public function curlRequest($url, $data = '') {
        $return = array('state' => 0, 'message' => '', 'result' => '', 'errNo' => 0);
        
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept-Language: zh-cn',
                'Connection: Keep-Alive',
                'Cache-Control: no-cache',
                'Content-type: application/x-www-form-urlencoded;charset=UTF-8'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            //设置超时时间
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            //API返回数据
            $apiResult = curl_exec($ch);
    
            $errNo = curl_errno($ch);
            if ($errNo) {
                //返回错误码
                $return['errNo'] = $errNo;
                $errorStr = curl_error($ch);
                switch ((int)$errNo) {
                    case 6: //避免一直发邮件 URL报错
                        break;
                    case 7: //无法通过 connect() 连接至主机或代理服务器
                        break;
                    case 28: //超时
                        break;
                    case 56: //接收网络数据失败
                        break;
                    default:
                        break;
                }
            }
                
            curl_close($ch);
            $return['state'] = 1;
            //返回数据
            $return['result'] = $apiResult;

        return $return;
    }

    //转单号元子段
    public function ConversionNumberYuanSubSegment()
    {
        $count = Db::name('yuan_subsegment')
            ->where('status',0)
            ->count();
            
        echo "临时打元子段".$count . PHP_EOL;
        halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        
        
        for ($i = 1; $i <= $page; $i++){
            $apconsumer = Db::name('yuan_subsegment')
                ->where('status',0)
                ->limit($pageSize)
                ->select()->toarray();
            foreach ($apconsumer as $v){
                $executedCount++;

                $order_achievement = DB::name('order_achievement')->field('order_id,shop_id')->where('tracking_number',$v['waybill_no'])->find();

                if(!empty($order_achievement) && !empty($v['waybill_no_new'])){
                    $executedCountsu++;
                    $shop_info = Db::name('shops')->where('id',$order_achievement['shop_id'])->find();
                    $this->add_metafield_transfer($order_achievement['order_id'],$shop_info,$v['waybill_no_new']);
                    $update['status'] = 1;
                }else{
                    $update['status'] = 2;
                }
                
                Db::name('yuan_subsegment')
                    ->where('id',$v['id'])
                    ->update($update);
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
            }
        }
    }

    public function add_metafield_afterpay($order_id,$shop_info,$apconsumer){
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$order_id."/metafields.json";  
        
        $post = array();
        $post['metafield']['namespace'] = 'custom';
        $post['metafield']['key'] =  'afterpay';
        $post['metafield']['value'] = $apconsumer['dispute_id'];
        // $post['metafield']['value'] = json_encode($post['metafield']['value'], true);
        $post['metafield']['type'] = 'single_line_text_field';
        // halt($post);
        $return = HttpUtil::PostUrl($url,$post, $shop_info);
        $return = json_decode($return, true);
        if(!empty($return['errors']) || !empty($return['error'])){
            $update['uploadstatus'] = 3;
            Db::name('order_dispute_apconsumer')
                ->where('id',$apconsumer['id'])
                ->update($update);
            return true;
        }else{
            $update['uploadstatus'] = 1;
            Db::name('order_dispute_apconsumer')
                ->where('id',$apconsumer['id'])
                ->update($update);
            return true;
        } 
    }

    public function add_metafield_transfer($order_id,$shop_info,$waybill_no_new){
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$order_id."/metafields.json";  
        
        $post = array();
        $post['metafield']['namespace'] = 'custom';
        $post['metafield']['key'] =  '_zhuandanhao';
        $post['metafield']['value'] = $waybill_no_new;
        // $post['metafield']['value'] = json_encode($post['metafield']['value'], true);
        $post['metafield']['type'] = 'single_line_text_field';
        // halt($post);
        $return = HttpUtil::PostUrl($url,$post, $shop_info);
        $return = json_decode($return, true);
        return true;
    }

    //争议数据对应到订单Shopify
    public function DisputeToOrdersShopify(){
        $t1       = microtime(true);

        // $update_achievement = [
        //     'disputeapi_status' => "暂无争议",
        //     'dispute' => 0,
        // ];
        // Db::name('order_achievement')
        //     ->where('disputeapi_type',"shopify")
        //     ->update($update_achievement);

        // $update2['createtime'] = 0;
        // $count = Db::name('order_dispute_api')
        //     ->where('id',">",0)
        //     ->update($update2);

        $count = Db::name('order_dispute_api')
            // ->where('email',"=",null)
            ->where('initiated_at',">=",date('Y-m-d', strtotime('-3 month')))
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_dispute_api')
                ->field('
                        id,
                        shop_id,
                        order_id,initiated_at,
                        status
                    ')
                // ->where('email',"=",null)
                ->where('initiated_at',">=",date('Y-m-d', strtotime('-3 month')))
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                $order_achievement = Db::name('order_achievement')->where('order_id',$v['order_id'])->find();
                $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                //更新会话
                if(!empty($order_customer['email'])){
                    $conversations = Db::name('conversations')
                        ->where('email',$order_customer['email'])
                        ->count();
                }else{
                    $conversations = 0;
                }
                $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                //找到争议
                $update = [
                    'conversations' => $conversations,
                    'email' => $order_customer['email'] ?? "",
                    'createtime' => $order_achievement['createtime'],
                    'shop_id' => $order_achievement['shop_id'] ?? "",
                    'order_name' => $order_achievement['name'] ?? "",
                    'financial_status' => $order_achievement['financial_status'] ?? "",
                    'fulfillment_status' => $order_achievement['fulfillment_status'] ?? "",
                    'tracking_number' => $order_achievement['tracking_number'] ?? "",
                    'disputetime' => $this->dateTimeStr($v['initiated_at']),
                    'OrderDeliveryTime' => $order_fulfillments['created_at'] ?? "",
                ];
                
                Db::name('order_dispute_api')
                    ->where('id',$v['id'])
                    ->update($update);
                //修改争议金额
                $v['status'] = $this->ChangeState($v['status'],'shopify');
                $v['dispute'] = $this->ChangeAmount($v['status'],'shopify');
                $update_achievement = [
                    'order_id' => $order_achievement['order_id'],
                    'disputeapi_type' => "shopify",
                    'disputeapi_status' => $v['status'] ??"暂无争议",
                    'dispute' => $v['dispute'],
                ];
                // halt($update_achievement);
                Db::name('order_achievement')
                    ->where('order_id',$order_achievement['order_id'])
                    ->update($update_achievement);
                $executedCountsu++;
                    
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
    * @desc    更新争议状态跟金额
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function UpdateDisputeStatusAndAmount()
    {
        $t1       = microtime(true);
        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where = [];
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        // $where[]  = ['order_id', '=', 5264082960441]; 

        // $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];    
        // $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        
        // halt($where);

        $count = Db::name('order_achievement')
            ->where($where)
            ->where('disputeapi_status',"<>","暂无争议")
            ->where('disputeapi_type',"<>","导入")
            // ->where('dispute',">",0)
            ->count();
            // halt($count);
            

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCountsu = 0;
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            // $group = Db::name('order_achievement')
            //     ->field('disputeapi_type')
            //     ->where($where)
            //     ->where('disputeapi_status',"<>","暂无争议")
            //     ->where('disputeapi_type',"<>","导入")
            //     ->group('disputeapi_type')
            //     ->select()->toarray();
            //     halt($group);
            
            // $group = Db::name('order_achievement')
            //     ->field('SUM(dispute) as dispute')
            //     ->where($where)
            //     ->where('disputeapi_status',"<>","暂无争议")
            //     ->where('disputeapi_type',"<>","导入")
            //     ->where('dispute',">",0)
            //     ->select()->toarray();
            //     halt($group);

            $list = Db::name('order_achievement')
                ->field('id,order_id,disputeapi_status,disputeapi_type')
                ->where($where)
                ->where('disputeapi_status',"<>","暂无争议")
                ->where('disputeapi_type',"<>","导入")
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
            foreach ($list['data'] as $v){
                $disputes = 0;
                switch ($v['disputeapi_type']) {
                    case 'stripe':
                        $order_dispute = Db::name('order_dispute_stripe')->field('status')->where('order_id',$v['order_id'])->find();
                        $order_dispute['status'] = $order_dispute['status'] ?? 0;
                        $order_dispute['status'] = $this->ChangeState($order_dispute['status'],'stripe');
                        $disputes = $this->ChangeAmount($order_dispute['status'],'stripe');
                        break;
                    case 'paypal':
                        $order_dispute = Db::name('order_dispute_paypal')->field('status')->where('order_id',$v['order_id'])->find();
                        $order_dispute['status'] = $order_dispute['status'] ?? 0;
                        $order_dispute['status'] = $this->ChangeState($order_dispute['status'],'paypal');
                        $disputes = $this->ChangeAmount($order_dispute['status'],'paypal');
                        break;
                    case 'shopify':
                        $order_dispute = Db::name('order_dispute_api')->field('status')->where('order_id',$v['order_id'])->find();
                        $order_dispute['status'] = $order_dispute['status'] ?? 0;
                        $order_dispute['status'] = $this->ChangeState($order_dispute['status'],'shopify');
                        $disputes = $this->ChangeAmount($order_dispute['status'],'shopify');
                        break;
                    case 'afterpay':
                        $order_dispute = Db::name('order_dispute_afterpay')->field('status')->where('order_id',$v['order_id'])->find();
                        $order_dispute['status'] = $order_dispute['status'] ?? 0;
                        $order_dispute['status'] = $this->ChangeState($order_dispute['status'],'afterpay');
                        $disputes = $this->ChangeAmount($order_dispute['status'],'afterpay');
                        break;
                    case 'airwallex':
                        $order_dispute = Db::name('order_dispute_airwallex')->field('status')->where('order_id',$v['order_id'])->find();
                        $order_dispute['status'] = $order_dispute['status'] ?? 0;
                        $order_dispute['status'] = $this->ChangeState($order_dispute['status'],'airwallex');
                        $disputes = $this->ChangeAmount($order_dispute['status'],'airwallex');
                        break;
                    default:
                        $disputes = 0;
                }
                if($disputes > 0){
                    $update = [];
                    $update['dispute'] = $disputes;
                    Db::name('order_achievement')->where('id',$v['id'])->update($update);
                    $executedCountsu++;
                }
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "ID:".$v['id'].",总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . ',成功：'.$executedCountsu.',剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;

    }
    
    

    //争议数据统计成每个月的报表
    public function DisputeToMonthlyReports(){
        $t1 = microtime(true);

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        // halt($date_msg);
        $where = [];
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 

        $lists = Db::name('order_achievement')
            ->field('
                COUNT(id) as quantity,
                sum(dispute) as dispute,
                disputeapi_type,
                disputeapi_status
            ')
            ->where($where)
            // ->where('shop_id',17)
            ->where('disputeapi_type',"<>",'')
            ->group('disputeapi_type,disputeapi_status')
            ->select()->toarray();
            
        //处理数组
        $shopOrderTotals = [];  
        foreach ($lists as $item) {  
            if (!isset($shopOrderTotals[$item['disputeapi_type']])) {  
                $info = [  
                    'quantity' => $item['quantity'],
                    'dispute' => $item['dispute'],
                    'disputeapi_type' => $item['disputeapi_type'],
                    'children' => [],
                ];
                $shopOrderTotals[$item['disputeapi_type']] = $info;
                $shopOrderTotals[$item['disputeapi_type']]['children'][] = $item;
            } else {   
                $shopOrderTotals[$item['disputeapi_type']]['quantity'] += (int)$item['quantity'] ?? 0;
                $shopOrderTotals[$item['disputeapi_type']]['dispute'] += (int)$item['dispute'] ?? 0;
                $shopOrderTotals[$item['disputeapi_type']]['children'][] = $item;
            }  
        }
        
        $lists = array_values($shopOrderTotals);  
        // halt($lists);
        
        $insert = [];
        foreach ($lists as &$v) { 
            $needs_response = 0;
            $under_review = 0;
            $won = 0;
            $lost = 0;
            $other = 0;
            foreach ($v['children'] as $ki=>$vi) {
                switch ($vi['disputeapi_status']) {
                    case '待处理':
                        $needs_response = (int)$vi['quantity'];
                        break;
                    case '审核中':
                        $under_review = (int)$vi['quantity'];
                        break;
                    case '争议赢':
                        $won = (int)$vi['quantity'];
                        break;
                    case '争议输':
                        $lost = (int)$vi['quantity'];
                        break;
                    case '其他':
                        $other = (int)$vi['quantity'];
                        break;
                    default:
                }
            }
            $insert[] = [
                'type' => $v['disputeapi_type'],
                'total_order' => $v['quantity'],
                'dispute' => $v['dispute'],
                'timedate' => $start_time,
                'month' => date("Y-m", $start_time),
                'needs_response' => $needs_response,
                'under_review' => $under_review,
                'won' => $won,
                'lost' => $lost,
                'other' => $other,
            ];
        }
        
        if(!empty($insert)){
            Db::name('report_monthly_dispute')
                ->where('timedate',$start_time)
                ->delete();
            Db::name('report_monthly_dispute')->insertAll($insert);
        }
        echo PHP_EOL . "DisputeToMonthlyReports-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //手动更新争议状态跟金额
    public function ManuallyUpdateDisputeStatusAndAmount(){
        $t1 = microtime(true);

        $msg = '争议输'; 
        $dispute = 15;
        // $msg = '审核中';
        // $dispute = 0;

        $count = Db::name('ordercheck_dispute')
            ->where('status',0)
            ->where('timedate',1727712000)
            // ->where('type',$msg)
            ->count();
// halt($count);
        $ordercheck_dispute = Db::name('ordercheck_dispute')
            ->where('status',0)
            ->where('timedate',1727712000)
            // ->where('type',$msg)
            ->select()->toarray();
        if($ordercheck_dispute){
            foreach ($ordercheck_dispute as $k=>$v) {
                $update_achievement = [
                    'disputeapi_type' => "shopify",
                    'disputeapi_status' => $msg,
                    'dispute' => $dispute,
                ];
                Db::name('order_achievement')
                    ->where('name',$v['transfer_number'])
                    ->where('shop_id',17)
                    ->update($update_achievement);
                Db::name('ordercheck_dispute')->where('id',$v['id'])->update(['status'=>1]);
                echo PHP_EOL . "总共".$count."条，修改成功".$k . PHP_EOL;
            }
            
        }
        echo PHP_EOL . "DisputeToMonthlyReports-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
    * @desc    通道状态
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ChangeState($status,$type)
    {
        if($type == 'stripe'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'paypal'){
            switch ($status) {
                case 'WAITING_FOR_SELLER_RESPONSE':
                    $status = '待处理';
                    break;
                case 'UNDER_REVIEW':
                    $status = '审核中';
                    break;
                case 'RESOLVED':
                    $status = '争议赢';
                    break;
                case 'LOST':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'afterpay'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'shopify'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'airwallex'){
            switch ($status) {
                case 'LOST':
                    $status = '争议输';
                    break;
                case 'ACCEPTED':
                    $status = '争议输';
                    break;
                case 'WON':
                    $status = '争议赢';
                    break;
                case 'CHALLENGED':
                    $status = '审核中';
                    break;
                default:
                    $status = '其他';
            }
        }
        return $status;
    }

    /**
    * @desc    通道金额
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ChangeAmount($status,$type)
    {
        //美金
        $dispute = 0;
        if($status == '争议输'){
            switch ($type) {
                case 'stripe':
                    $dispute = 17;
                    break;
                case 'paypal':
                    $dispute = 8;
                    break;
                case 'shopify':
                    $dispute = 15;
                    break;
                case 'afterpay':
                    $dispute = 15;
                    break;
                case 'airwallex':
                    $dispute = 15;
                    break;
                default:
                    $dispute = 15;
            }
        }
        return $dispute;
    }
    
    /**
    * @desc    搜索月份
    * @date    2024/9/19
    * @author  zhangheng
    */
    public function SearchMonth()
    {
        // $date = date('Y-m', time()); 
        $date = date('Y-m', strtotime('-3 month'));
        $date_msg = date('Y年m月', strtotime('-3 month'));
        $start_time = date('Y-m-01', strtotime('-3 month'));
        $end_time = strtotime(date("Y-m-d", strtotime("$start_time +1 month"))) - 1;
        $start_time = strtotime($start_time);
        return [$date,$date_msg, $start_time, $end_time];
    }
    
    // 恢复日志
    public function RestoreLogs(){
        $t1       = microtime(true);
        $count = Db::name('order_source_log')
            ->where('shop_id',17)
            ->count();
            // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_source_log')
                ->field('source_id as id,tag_source,tag_campaign')
                ->where('id',">=",0)
                ->where('shop_id',17)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
            foreach ($list['data'] as $v){
                Db::name('order_source')
                    ->where('id',$v['id'])
                    ->update($v);
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    
    /**
    * @desc    恢复匹配
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function RestoreMatch()
    {
        // $update_source['status'] = 0;
        // $counts = Db::name('order_source')
        //     ->where('tag_campaign',"=","LabelIsEmpty")
        //     ->where('shop_id',"=",17)
        //     ->where('createtime',">=",1732982400)
        //     ->where('createtime',"<=",1735660800)
        //     ->update($update_source);
        // halt($counts);
        $counts = Db::name('order_source')
            ->where('tag_source',"=",'LabelIsEmpty')
            ->where('shop_id',"=",17)
            ->where('createtime',">=",1732982400)
            ->where('createtime',"<=",1735660800)
            ->count();
            // halt($counts);
            
        $customerjourneys = Db::name('order_source')
            ->field('id')
            ->where('tag_source',"=",'LabelIsEmpty')
            ->where('shop_id',"=",17)
            ->where('createtime',">=",1732982400)
            ->where('createtime',"<=",1735660800)
            ->order('order_number desc')
            ->limit(10000)
            ->select()->toarray();
        foreach ($customerjourneys as $k=>$customerjourney) {
            $order_source_log = Db::name('order_source_log')->where('source_id',$customerjourney['id'])->order('id desc')->find();
            halt($order_source_log);
            if ($order_source_log) {
                $update['tag_source'] = $order_source_log['tag_source'];
                $update['tag_campaign'] = $order_source_log['tag_campaign'];
                Db::name('order_source')
                    ->where('id',$customerjourney['id'])
                    ->update($update);
            }
            
            echo PHP_EOL . "总共".$counts.",已执行:" . $k ."--" . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-完成" . PHP_EOL;
    }
    /**
    * @desc    新独立站-shopify客户来源匹配标签
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function customerj_handle()
    {
        // $update_source["tag_source"] = "LabelIsEmpty";
        // $update_source["tag_campaign"] = "LabelIsEmpty";
        // $update_source['status'] = 0;
        // $counts = Db::name('order_source')
        //     ->where('tag_campaign',"=",'LabelIsEmpty')
        //     ->where('shop_id',"in",[17,21,18])
        //     ->where('createtime',">=",1751644800)
        //     ->where('createtime',"<=",1751817600)
        //     ->update($update_source);
        // halt($counts);
        $counts = Db::name('order_source')
            ->where('status',0)
            // ->where('tag_source',"=",'LabelIsEmpty')
            ->where('shop_id',"in",[17,21,18])
            ->where('createtime',">=",1751644800)
            ->where('createtime',"<=",1751817600)
            ->count();
            // halt($counts);
            
        $customerjourneys = Db::name('order_source')
            ->where('status',0)
            // ->where('tag_source',"=",'LabelIsEmpty')
            ->where('shop_id',"in",[17,21,18])
            ->where('createtime',">=",1751644800)
            ->where('createtime',"<=",1751817600)
            ->order('order_number desc')
            ->limit(10000)
            ->select()->toarray();
        $ApiOrderLogic = new ApiOrderLogic();
        foreach ($customerjourneys as $k=>$customerjourney) {
            $order_source = $ApiOrderLogic->customerjourney($customerjourney);
            //自动补全渠道标签
            if($order_source['tag_source'] == "LabelIsEmpty" && $order_source['tag_campaign'] !== "LabelIsEmpty"){
                $order_source['tag_source'] = $ApiOrderLogic->tag_campaign_tag($order_source["tag_campaign"]);
            }
            $update = [];
            $update["tag_source"] = $order_source['tag_source'];
            $update["tag_campaign"] = $order_source['tag_campaign'];
            $update['status'] = 1;
            if($update["tag_source"] == "other"){
                $update['status'] = 2;
            }
            Db::name('order_source')
                ->where('id',$customerjourney['id'])
                ->update($update);
            echo PHP_EOL . "总共".$counts.",已执行:" . $k ."--" . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-完成" . PHP_EOL;
    }
    

    public function QueryAdvertisingData()
    {
        //读取txt文件
        // D:\WWW\yile_new\shopify_new_back/20241206.txt
        $file = fopen("D:\WWW\yile_new\shopify_new_back/20241206.txt", "r");
        $inserts = [];
        while (!feof($file)) {
            $str = fgets($file);
            $str = trim($str);
            if(!empty($str)){
                // if ($this->isValidDate($str)) {
                //     $newdata = [];
                //     $newdata['date'] = $str;
                // }
                if ($this->isValidJson($str)) {
                    $str_data = json_decode($str, true);
                    $str_data = $str_data['AdvertisingApiLog'];
                    $insert = [];
                    $insert['advertiser_id'] = $str_data['advertiser_id'];
                    $insert['stat_time_day'] = $str_data['stat_time_day'];
                    $insert['spend'] = $str_data['spend'] ?? 0;
                    $str_data['createtime'] = $str_data['createtime'] ?? 0;
                    if($str_data['createtime'] > 0){
                        $insert['createtime'] = date('Y-m-d H:i:s', $str_data['createtime']);
                    }else{
                        $insert['createtime'] = 0;
                    }
                    $inserts[] = $insert;
                }
            }
        }
        Db::name('advertising_apilog')->insertAll($inserts);
    }
    
    public function isValidDate($dateString) {
        $pattern = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/';
        if (preg_match($pattern, $dateString)) {
            $timestamp = strtotime($dateString);
            if ($timestamp !== false && date('Y-m-d H:i:s', $timestamp) === $dateString) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    public function isValidJson($json) {
        json_decode($json);
        return (json_last_error() == JSON_ERROR_NONE);
    }

    /**
    * @desc    重新整理sku
    * @date    2024/12/27
    * @author  zhangheng
    */
    public function ReorganizeSKU($order_id)
    {
        $update = [];
        $update['sku_info'] = "未知";
        $order_skuinfo = DB::name('order_skuinfo')
            ->field('new_sku, SUM(realcount) as total_realcount')
            ->where('order_id', $order_id)
            ->group('new_sku')
            ->select()
            ->toArray();
        $new_sku_strings = [];
        if(!empty($order_skuinfo)){
            foreach ($order_skuinfo as $item) {
                if($item['total_realcount'] > 1){
                    $new_sku_strings[] = $item['new_sku'] . '-' . $item['total_realcount'];
                }else{
                    $new_sku_strings[] = $item['new_sku'];
                }
            }
            $new_sku = implode(',', $new_sku_strings);
            $update['sku_info'] = $new_sku ? $new_sku : "未知";
        }
        return $update;
    }

    /**
    * 统计sku
    * @param array params
    */
    public function CountTheNumberOfSkus($sku = '')
    {
        $Number = 0;
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                //数量
                $km = count($sku) - 1;
                $numeric = is_numeric($sku[$km]) ? true : false;
                $Number = 1;
                if($numeric && $sku[$km] < 25){
                    //是数字并且小于100才计算数量
                    $Number = $sku[$km];
                }
                
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    $kmPlus = count($skuPlus);
                    if($kmPlus >= 1){
                        $Number = $Number * $kmPlus;
                    }
                }
            }
        }
        return $Number;
    }

    /**
    * @desc    拆分sku成个体
    * @date    2024/12/27
    * @author  zhangheng
    */
    public function SplitSkusIntoIndividuals($sku)
    {
        // $sku = 'black-4XL,bra126-black-40E';
        $sku_map = explode(',', $sku);
        $sku_map_new = [];
        foreach ($sku_map as $k=>$v) {
            $pos = strpos($v, '-');
            if($pos !== false){
                $sku = explode('-',$v);
                //数量
                $km = count($sku) - 1;
                $numeric = is_numeric($sku[$km]) ? true : false;
                $Number = 1;
                if($numeric && $sku[$km] < 25){
                    //是数字并且小于100才计算数量
                    $Number = $sku[$km];
                }
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    foreach ($skuPlus as $key => $value) {
                        if (!isset($sku_map_new[$sku[0] . '-' . $value . '-' . $sku[2]])) {
                            $sku_map_new[$sku[0] . '-' . $value . '-' . $sku[2]] = 0;
                        }
                        $sku_map_new[$sku[0] . '-' . $value . '-' . $sku[2]] += (int)$Number;
                    }
                }else{
                    if (!isset($sku_map_new[$v])) {
                        $sku_map_new[$v] = 0;
                    }
                    $sku_map_new[$v] += (int)$Number;
                }
            }
        }
        $new_sku_strings = [];
        if(!empty($sku_map_new)){
            foreach ($sku_map_new as $k=>$v) {
                if($v > 1){
                    $new_sku_strings[] = $k . '-' . $v;
                }else{
                    $new_sku_strings[] = $k;
                }
            }
        }
        // halt($new_sku_strings);
        return $new_sku_strings;
    }



    /**
     * @desc    AddTags_tro04b
     * @author zhangheng
     * @date   2024-12-31
     */
    public function AddTags_tro04b(){

        $order_varient = Db::name('order_varient_log')
            ->where('line_item_id','<>',"")
            ->where('order_id','=',5186771288121)
            ->select();
        foreach ($order_varient as $k=>$v) {
            $order_id = $v['order_id']??0;
            $shop_id = $v['shop_id']??0;
            if(empty($order_id) || empty($order_id)){
                echo '缺少订单id或店铺id';
            }
            $shop_info = Db::name('shops')->where('id',$shop_id)->find();
            $order_info = Db::name('order_achievement')->field('tags')->where('order_id',$order_id)->find();
            $url = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id.".json";
            $tags = !empty($order_info['tags']) ? $order_info['tags'] . ",tro04b+1" : "tro04b+1";
            $data = [
                'order' => [
                    'id' => $order_id,
                    'tags' => $tags,
                ],
            ];
            // halt($url);
            $return = HttpUtil::PutUrl($url, $data, $shop_info);
            $res  = json_decode($return, true);
            // halt($res);
            if(!empty($res['errors']) || !empty($res['error'])){
                echo $res['errors'];
                echo $res['error'];
            }
            echo $order_id. "完成" .PHP_EOL;
        }
        echo PHP_EOL . "所有完成" . PHP_EOL;
    }


    public function contacts_update()
    {
        // $update['brand'] = 'SheCurve';
        // $count = Db::name('contacts')->where('brand','=',null)->count();
        // halt($count);
        // die;
        $brands = [
            0 => 'LilyLove',
            1 => '4304ef',
            2 => 'SheCurve',
        ];
        foreach($brands as $key => $val){
            $this->contacts_updateinfo($val);
        }
    }

    public function contacts_updateinfo($brand)
    {
        echo "新增reamaze联系人" . PHP_EOL;
        $page = 20;
        for ($i = 1; $i <= $page; $i++){
            $this->contacts($i,$brand);
            echo $i . "完成" . PHP_EOL;
        }
    }
    
    public function contacts($page,$brand = 'SheCurve')
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        // 消息列表
        $url = 'https://'.$brand.'.reamaze.io/api/v1/contacts?page='.$page.'&type=email&sort=date';
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        // halt($return);
        if(isset($return['contacts']) && !empty($return['contacts'])){
            $contacts = $return['contacts'];
            $count = 0;
            foreach($contacts as $key => $val){
                $count++;
                $insert = [
                    'name'              => $val['name'],
                    'created_at'            => $val['created_at'] ?? "",
                    'email'            => $this->removeNonAscii($val['email']) ?? "",
                    'contact_id'            => $val['_id'] ?? "",
                    'brand'            => $brand,
                ];
                $slug = Db::name('contacts')->where(['contact_id' => $val['_id']])->find();
                if($slug){
                    continue;
                }else{
                    echo "新增".$insert['created_at']."---".$insert['contact_id']. PHP_EOL;
                    try {
                        Db::name('contacts')->insert($insert);
                    } catch (\Throwable $e) {
                        echo "新增失败". PHP_EOL;  
                        continue;
                    }
                }
            }
            $page = $page + 1;
        }
        return true;
    }

    public function removeNonAscii($string) {  
        $output = '';  
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {  
            $char = mb_substr($string, $i, 1, 'UTF-8');  
            if (ord($char[0]) < 128) {  
                $output .= $char;  
            }  
        }  
        return $output;  
    } 


    /**
    * @desc    给visa打标签
    * @author  zhangheng
    */
    public function LabelVisa()
    {
        $count = Db::name('order_achievement')
            ->where('shop_id',17)
            ->where('card_status',0)
            ->where('payment_gateway_names',"shopify_payments")
            ->where('createtime',">=",1730390400)
            ->count();
        // $count = 100;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;
        $shop_id        = 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        for ($i = 1; $i <= $count; $i++){
            $update = [];
            $update['card_status'] = 2;
            $order = Db::name('order_achievement')
                ->field('shop_id,order_id,tags')
                ->where('shop_id',17)
                ->where('card_status',0)
                ->where('payment_gateway_names',"shopify_payments")
                ->where('createtime',">=",1730390400)
                ->order('createtime desc')
                ->find();
            $order_id        = $order['order_id'];
            $tags        = $order['tags'];
            $version        = Config('Logisticskey.shopify.api_versoin');
            $url            = $shop_info['myshopify_domain'].$version . "/orders/".$order['order_id']."/transactions.json";
            $return = HttpUtil::getUrl($url, $shop_info);
            if(!empty($return)){
                $transactions = $return['transactions'];
                foreach ($transactions as $k=>$vt) {
                    if(isset($vt['payment_details']['credit_card_company']) && isset($vt['gateway']) && $vt['gateway'] == 'shopify_payments' && $vt['payment_details']['credit_card_company'] == 'Mastercard'){
                        //打标签
                        $url = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id.".json";
                        $tags = !empty($tags) ? $tags . ",Master" : "Master";
                        $data = [
                            'order' => [
                                'id' => $order_id,
                                'tags' => $tags,
                            ],
                        ];
                        // halt($url);
                        $return = HttpUtil::PutUrl($url, $data, $shop_info);
                        // halt($return);
                        $update['card_status'] = 1;
                        $executedCountsu++;
                        break;
                    }
                }
            }
            $executedCount++;
            Db::name('order_achievement')
                ->where('order_id',$order_id)
                ->update($update);
            echo "总共".$count."条，订单：".$order_id."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
        }
    }
    
    
    /**
    * @desc    给visa打标签
    * @author  zhangheng
    */
    public function LabelPaypal()
    {
        $count = Db::name('order_achievement')
            ->where('shop_id',17)
            ->where('card_status',0)
            ->where('payment_gateway_names',"paypal")
            ->where('createtime',">=",1730390400)
            ->count();
        // $count = 100;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;
        $shop_id        = 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        for ($i = 1; $i <= $count; $i++){
            $update = [];
            $order = Db::name('order_achievement')
                ->field('shop_id,order_id,tags')
                ->where('shop_id',17)
                ->where('card_status',0)
                ->where('payment_gateway_names',"paypal")
                ->where('createtime',">=",1730390400)
                ->order('createtime desc')
                ->find();
            $order_id        = $order['order_id'];
            $tags        = $order['tags'];
            //打标签
            $url = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id.".json";
            $tags = !empty($tags) ? $tags . ",paypal" : "paypal";
            $data = [
                'order' => [
                    'id' => $order_id,
                    'tags' => $tags,
                ],
            ];
            // halt($url);
            $return = HttpUtil::PutUrl($url, $data, $shop_info);
            // halt($return);
            $update['card_status'] = 1;
            $executedCountsu++;
            
            $executedCount++;
            Db::name('order_achievement')
                ->where('order_id',$order_id)
                ->update($update);
            echo "总共".$count."条，订单：".$order_id."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
        }
    }
    

    /**
    * @desc    给mastercard打标签
    * @author  zhangheng
    */
    public function Labelmastercard()
    {
        die;
        $count = Db::name('order_achievement')
            ->where('shop_id',17)
            ->where('card_status',0)
            ->where('payment_gateway_names',"shopify_payments")
            ->where('createtime',">=",1730390400)
            ->count();
        // $count = 100;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;
        $shop_id        = 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        for ($i = 1; $i <= $count; $i++){
            $update = [];
            $update['card_status'] = 2;
            $order = Db::name('order_achievement')
                ->field('shop_id,order_id,tags')
                ->where('shop_id',17)
                ->where('card_status',0)
                ->where('payment_gateway_names',"shopify_payments")
                ->where('createtime',">=",1730390400)
                ->order('createtime desc')
                ->find();
            $order_id        = $order['order_id'];
            $tags        = $order['tags'];
            $version        = Config('Logisticskey.shopify.api_versoin');
            $url            = $shop_info['myshopify_domain'].$version . "/orders/".$order['order_id']."/transactions.json";
            $return = HttpUtil::getUrl($url, $shop_info);
            if(!empty($return)){
                $transactions = $return['transactions'];
                foreach ($transactions as $k=>$vt) {
                    if(isset($vt['payment_details']['credit_card_company']) && isset($vt['gateway']) && $vt['gateway'] == 'shopify_payments' && $vt['payment_details']['credit_card_company'] == 'Visa'){
                        //打标签
                        $url = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id.".json";
                        $tags = !empty($tags) ? $tags . ",VDMP" : "VDMP";
                        $data = [
                            'order' => [
                                'id' => $order_id,
                                'tags' => $tags,
                            ],
                        ];
                        // halt($url);
                        $return = HttpUtil::PutUrl($url, $data, $shop_info);
                        // halt($return);
                        $update['card_status'] = 1;
                        $executedCountsu++;
                        break;
                    }
                }
            }
            $executedCount++;
            Db::name('order_achievement')
                ->where('order_id',$order_id)
                ->update($update);
            echo "总共".$count."条，订单：".$order_id."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
        }
    }
    
    /**
    * @desc    海外仓打标签hwc
    * @author  zhangheng
    */
    public function WarehouseLabelHwc()
    {
        $count = Db::name('order_shopify_list')
            ->where('ship_status',4)
            ->where('label_status',0)
            ->count();
        echo "海外仓打标签有".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $count; $i++){
            $update = [];
            $update['label_status'] = 2;
            $order = Db::name('order_shopify_list')
                ->field('shop_id,order_id')
                ->where('ship_status',4)
                ->where('label_status',0)
                ->order('id desc')
                ->find();
            $order_achievement = Db::name('order_achievement')
                ->field('tags')
                ->where('order_id',$order['order_id'])
                ->find();
            
            $shop_id        = $order['shop_id'];
            $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
            $order_id        = $order['order_id'];
            $tags        = $order_achievement['tags'];
            //打标签
            $url = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id.".json";
            $tags = !empty($tags) ? $tags . ",hwc" : "hwc";
            $data = [
                'order' => [
                    'id' => $order_id,
                    'tags' => $tags,
                ],
            ];
            // halt($url);
            $return = HttpUtil::PutUrl($url, $data, $shop_info);
            // halt($return);
            $update['label_status'] = 1;
            $executedCountsu++;
            $executedCount++;
            Db::name('order_shopify_list')
                ->where('order_id',$order_id)
                ->update($update);
            echo "总共".$count."条，订单：".$order_id."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
        }
    }
    /**
    * @desc    邮件改状态
    * @author  zhangheng
    */
    public function conversations_update()
    {
        //修改
        // $count = $list = Db::name('contacts')
        //     ->where('update_type',"<>",1)
        //     ->where('created_at',">=","2025-06-01")
        //     ->where('created_at',"<=","2025-07-01")
        //     ->update([
        //         'update_type' => 0
        //     ]);
        // halt($count);

        $t1       = microtime(true);
        $count = $list = Db::name('contacts')
            ->where('update_type',0)
            ->where('created_at',">=","2024-11-01")
            ->count();
            
        // echo "工单合并".$count . PHP_EOL;
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('contacts')
                ->where('update_type',0)
                ->where('created_at',">=","2024-11-01")
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                // 新判断条件
                // $conversations = Db::name('conversations')->where('author',$v['name'])->find();
                // if(!isset($conversations)){
                //     $update['update_type'] = 4;
                //     Db::name('contacts')->where('id',$v['id'])->update($update);
                //     $executedCount++;
                //     $num = $count - $executedCount;
                //     echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前邮箱'.$v['id'].$v['email'].',第' .$i.'页' . PHP_EOL;
                //     continue;
                // }
                // if(isset($conversations['message_count']) && $conversations['message_count'] <= 1){
                //     $update['update_type'] = 5;
                //     Db::name('contacts')->where('id',$v['id'])->update($update);
                //     $executedCount++;
                //     $num = $count - $executedCount;
                //     echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前邮箱'.$v['id'].$v['email'].',第' .$i.'页' . PHP_EOL;
                //     continue;
                // }
                $update = [];
                if(!empty($v['email'])){
                    $return_con = $this->conversations_info($v);
                    if($return_con){
                        $executedCountsu++;
                        $update['update_type'] = 1;
                    }else{
                        $update['update_type'] = 2;
                    }
                }else{
                    $update['update_type'] = 3;
                }
                Db::name('contacts')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前邮箱'.$v['id'].$v['email'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function conversations_info($v)
    {
        $emails = $v['email'] ?? '';
        $brand = $v['brand'] ?? 'SheCurve';
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations?page=1&filter=open&sort=updated_at&for='.$emails;
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        if(isset($return['conversations']) && !empty($return['conversations'])){
            $conversations = $return['conversations'];
            $count = count($conversations);
            if($count > 1){
                foreach($conversations as $key => $val){
                    if($key == 0){
                        continue;
                    }
                    $this->conversations_update_status($val['slug'],$brand);
                }
                return true;
            }
            return false;
        }else{
            return false;
        }
    }
    
    public function conversations_update_status($slug,$brand)
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug;
        $data['conversation']['status'] = 2;
        HttpUtil::putUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        return true;
    }
    
    /**
    * 客户行为日志
    * @param array params
    */
    public function CustomerBehaviorLog()
    {
        // $update_source['graphql_status'] = 0;
        // $count = Db::name('order_source')
        //     ->where('tag_campaign',"=","LabelIsEmpty")
        //     // ->where('graphql_status',0)
        //     ->where('order_id',"<>","")
        //     ->where('shop_id',"in",[17,21,18])
        //     ->where('createtime',">=",1746028800)
        //     ->where('createtime',"<=",1748707200)
        //     ->update($update_source);
        // halt($count);

        $count = Db::name('order_source')
            // ->where('tag_campaign',"=","LabelIsEmpty")
            ->where('graphql_status',0)
            ->where('order_id',"<>","")
            ->where('shop_id',"in",[17,21,18])
            ->where('createtime',">=",1751644800)
            ->where('createtime',"<=",1751817600)
            ->count();
            // halt($count);
        $executedCount = 0;
        for ($i = 1; $i <= $count; $i++){
            $executedCount++;
            $order = Db::name('order_source')
                ->where('graphql_status',0)
                ->where('order_id',"<>","")
                ->where('shop_id',"in",[17,21,18])
                ->where('createtime',">=",1751644800)
                ->where('createtime',"<=",1751817600)
                ->order('createtime asc')
                ->find();
            if(empty($order)){
                echo PHP_EOL . "暂无数据" . PHP_EOL;
            }
            $shop_info = Db::name('shops')
                ->where('id', $order['shop_id'])
                ->find();
            $ApiOrderLogic = new ApiOrderLogic();
            $ApiOrderLogic->customer($order['order_id'],$shop_info['app_secret'],$shop_info['myshopify_domain']);
            echo "总共".$count."条数据，已完成".$executedCount."条" . PHP_EOL;
        }
    }

    //客服查看标签
    public function CustomerServiceViewTags()
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        // 消息列表
        $url = 'https://SheCurve.reamaze.io/api/v1/reports/tags?start_date=2025-01-15';
        $url = 'https://SheCurve.reamaze.io/api/v1/reports/tags';
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        halt($return);
        
    }

    //客服查看详情
    public function CustomerServiceViewDetails()
    {
        $slug = 'order-number-631538';
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://SheCurve.reamaze.io/api/v1/conversations/'.$slug;
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        halt($return);
    }


    public function dispute_status_update()
    {
        $update_dispute['dispute_status'] = 0;
        Db::name('order')
            ->where('createtime',">=",strtotime('-3 month'))
            ->where('shop_id',17)
            ->update($update_dispute);
    }

    public function Apireamaze()
    {
        $brands = [
            0 => 'SheCurve',
            1 => '4304ef',
            2 => 'LilyLove',
        ];
        foreach($brands as $key => $val){
            // $this->Apireamazeinfo($val);
            $this->Apireamazeinfo2($val);
        }
    }

    public function Apireamazelabel()
    {
        $brands = [
            0 => 'SheCurve',
            1 => '4304ef',
            2 => 'LilyLove',
        ];
        foreach($brands as $key => $val){
            $this->Apireamazeinfo($val);
        }
    }

    public function Apireamazeinfo2($brand)
    {
        echo $brand."新增消息会话" . PHP_EOL;
        //查找页数
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
            $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations?filter=all&sort=updated_at';
            $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
            $page = $return['page_count'] ?? 0;
            if($page > 0){
                echo "有".$page."页". PHP_EOL;
                for ($i = 1; $i <= 4000; $i++){
                    $this->Apireamazes2($i,$brand);
                    echo $i . "完成" . PHP_EOL;
                }
            }
    }
    
    public function Apireamazes2($page,$brand = 'SheCurve')
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        // 消息列表
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations?page='.$page.'&filter=all&sort=updated_at';
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        // halt($return['page_count']);
        if(isset($return['conversations']) && !empty($return['conversations'])){
            $conversations = $return['conversations'];
            $count = 0;
            foreach($conversations as $key => $val){
                $count++;
                if($val['category']['channel'] !== 1){
                    continue;
                }
                $slug = Db::name('conversations')->where(['slug' => $val['slug']])->find();
                if($slug){
                    $update = [
                        'status'              => $val['status'] ?? "",
                        'tag_list'          => json_encode($val['tag_list'],true) ?? "",
                        'created_at'        => getDateTime($val['created_at']),
                        'order_time'        => getDateTime($val['created_at']),
                        'updated_at'        => getDateTime($val['updated_at']),
                        'channel'        => $val['category']['channel'] ?? "",
                        'brand'        => $brand,
                        'email'        => $val['author']['email'] ?? "",
                        'assignee_email'        => $val['assignee']['email'] ?? "",
                    ];
                    echo $brand."修改".$update['created_at']."---".$val['slug']."---".$val['status']. PHP_EOL;
                    try {
                        Db::name('conversations')->where(['slug' => $val['slug']])->update($update);
                    } catch (\Throwable $e) {
                        echo "修改失败". PHP_EOL;  
                        continue;
                    }
                }else{
                    $insert = [
                        'subject'           => $this->removeNonAscii($val['subject']),
                        'slug'              => $val['slug'],
                        'tag_list'          => json_encode($val['tag_list'],true) ?? "",
                        'status'            => $val['status'] ?? "",
                        'author'            => $this->removeNonAscii($val['author']['name']),
                        'message_count'     => $val['message_count'],
                        'created_at'        => getDateTime($val['created_at']),
                        'order_time'        => getDateTime($val['created_at']),
                        'updated_at'        => getDateTime($val['updated_at']),
                        'channel'        => $val['category']['channel'] ?? "",
                        'email'        => $val['author']['email'] ?? "",
                        'assignee_email'        => $val['assignee']['email'] ?? "",
                        'json'              => $this->removeNonAscii(json_encode($val,true)),
                        'brand'        => $brand,
                    ];
                    echo $brand."新增".$insert['created_at']."---".$insert['slug']. PHP_EOL;
                    try {
                        Db::name('conversations')->insert($insert);
                    } catch (\Throwable $e) {
                        echo "新增失败". PHP_EOL;  
                        continue;
                    }
                }
            }
        }
        return true;
    }

    public function Apireamazeinfo($brand)
    {
        echo $brand."新增消息会话" . PHP_EOL;
        //查找页数
        $list = Config('Logisticskey.emial_tags');
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        foreach($list as $key => $val){
            $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations?filter=all&sort=updated_at&tag='.$val;
            $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
            $page = $return['page_count'] ?? 0;
            if($page > 0){
                echo $val ."有".$page."页". PHP_EOL;
                for ($i = 1; $i <= $page; $i++){
                    $this->Apireamazes($i,$val,$brand);
                    echo $i . "完成" . PHP_EOL;
                }
                //统一删除
                $counts = Db::name('conversations')
                    ->where('status',2)
                    ->where('tags',$val)
                    ->where('brand',$brand)
                    ->count();
                if($counts > 0){
                    $slugs = Db::name('conversations')
                        ->where('status',2)
                        ->where('tags',$val)
                        ->where('brand',$brand)
                        ->select()->toarray();
                    $Deletecount = 0;
                    foreach($slugs as $ks => $slug){
                        $this->DeleteTagsinfo($slug,$brand);
                        $Deletecount++;
                        echo $val ."总共".$counts."个,已删除".$Deletecount. "个".PHP_EOL;
                    }
                    Db::name('conversations')
                        ->where('status',2)
                        ->where('tags',$val)
                        ->where('brand',$brand)
                        ->update([
                            'tags' => '',
                        ]);
                }
            }
        }
    }
    
    public function Apireamazes($page,$val,$brand = 'SheCurve')
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        // 消息列表
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations?page='.$page.'&filter=all&sort=updated_at&tag='.$val;
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        // halt($return['page_count']);
        if(isset($return['conversations']) && !empty($return['conversations'])){
            $conversations = $return['conversations'];
            $count = 0;
            foreach($conversations as $key => $val){
                $count++;
                if($val['category']['channel'] !== 1){
                    continue;
                }
                $slug = Db::name('conversations')->where(['slug' => $val['slug']])->find();
                if($slug){
                    $update = [
                        'status'              => $val['status'] ?? "",
                        'tag_list'          => json_encode($val['tag_list'],true) ?? "",
                        'created_at'        => getDateTime($val['created_at']),
                        'order_time'        => getDateTime($val['created_at']),
                        'updated_at'        => getDateTime($val['updated_at']),
                        'channel'        => $val['category']['channel'] ?? "",
                        'brand'        => $brand,
                        // 'email'        => $val['category']['email'] ?? "",
                    ];
                    echo $brand."修改".$update['created_at']."---".$val['slug']."---".$val['status']. PHP_EOL;
                    try {
                        Db::name('conversations')->where(['slug' => $val['slug']])->update($update);
                    } catch (\Throwable $e) {
                        echo "修改失败". PHP_EOL;  
                        continue;
                    }
                }else{
                    $insert = [
                        'subject'           => $this->removeNonAscii($val['subject']),
                        'slug'              => $val['slug'],
                        'tag_list'          => json_encode($val['tag_list'],true) ?? "",
                        'status'            => $val['status'] ?? "",
                        'author'            => $this->removeNonAscii($val['author']['name']),
                        'message_count'     => $val['message_count'],
                        'created_at'        => getDateTime($val['created_at']),
                        'order_time'        => getDateTime($val['created_at']),
                        'updated_at'        => getDateTime($val['updated_at']),
                        'channel'        => $val['category']['channel'] ?? "",
                        // 'email'        => $val['category']['email'] ?? "",
                        'json'              => $this->removeNonAscii(json_encode($val,true)),
                        'brand'        => $brand,
                    ];
                    echo $brand."新增".$insert['created_at']."---".$insert['slug']. PHP_EOL;
                    try {
                        Db::name('conversations')->insert($insert);
                    } catch (\Throwable $e) {
                        echo "新增失败". PHP_EOL;  
                        continue;
                    }
                }
            }
        }
        return true;
    }

    /**
    * @desc    修改标签
    * @author  zhangheng
    */
    public function ModifyTags()
    {
        $t1       = microtime(true);
        $count = $list = Db::name('conversations')
            ->where('tags_type',0)
            ->where('status',0)
            ->where('channel',1)
            ->where('updated_at',">=","2025-01-01")
            ->count();
        
        // halt($count);
        $pageSize = 600;

        //特殊标签
        $tags = [
            0 => "AAAAA",
            1 => "BBBBB",
            2 => "CCCCC",
            3 => "DDDDD",
            4 => "EEEEE",
            5 => "FFFFF",
            6 => "GGGGG",
            7 => "HHHHH",
            8 => "JJJJJ",
            9 => "KKKKK",
            10 => "LLLLL",
            11 => "MMMMM",
            12 => "NNNNN",
            13 => "OOOOO",
        ];
        foreach ($tags as $k => $v) {
            $updatec = Db::name('conversations')
                ->where('tags_type',0)
                ->where('status',0)
                ->where('channel',1)
                ->where('tag_list','like','%'.$v.'%')
                ->where('created_at',">=","2025-01-15")
                ->update(
                    [
                        'tags_type' => 3,
                        'tags' => $v,
                    ]
                );
                echo $v."修改标签".$updatec . PHP_EOL;
        }
        echo '查询完成' . PHP_EOL;

        $page     = count($tags);
        
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 0; $i < $page; $i++){
            // $tags[$i];
            $list = Db::name('conversations')
                ->where('tags_type',0)
                ->where('status',0)
                ->where('channel',1)
                ->where('updated_at',">=","2025-01-01")
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                //修改标签
                $return_con = $this->ModifyTagsinfo($v,$tags[$i]);
                if($return_con){
                    $executedCountsu++;
                    $update['tags_type'] = 1;
                    $update['tags'] = $tags[$i];
                }else{
                    $update['tags_type'] = 2;
                }
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['created_at'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
    * @desc    修改标签定制
    * @author  zhangheng
    */
    public function ModifyTagsCustomized()
    {
        $t1       = microtime(true);
// 12.1 --12.10
// 12.10.20
// 20-25
// 25-30 ddd
        $count = Db::name('conversations')
            ->where('update_type',0)
            ->where('status',0)
            ->where('channel',1)
            ->where('created_at',"<=","2024-12-30")
            ->where('created_at',">=","2024-12-25")
            ->count();
        
        // halt($count);
        $pageSize = 600;

        //特殊标签
        $tags = [
            // 0 => "AAAAA",
            // 1 => "BBBBB",
            // 2 => "CCCCC",
            // 3 => "DDDDD",
            // 4 => "EEEEE",
            // 5 => "FFFFF",
            // 6 => "GGGGG",
            // 7 => "HHHHH",
            // 8 => "JJJJJ",
            // 9 => "KKKKK",
            // 10 => "LLLLL"
        ];
        $tags = [
            0 => "DDDDD",
        ];
        $page     = count($tags);
        
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 0; $i < $page; $i++){
            // $tags[$i];
            $list = Db::name('conversations')
                ->where('update_type',0)
                ->where('status',0)
                ->where('channel',1)
                ->where('created_at',"<=","2024-12-30")
                ->where('created_at',">=","2024-12-25")
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                //修改标签
                $return_con = $this->ModifyTagsinfo($v,$tags[$i]);
                if($return_con){
                    $executedCountsu++;
                    $update['tags_type'] = 1;
                    $update['tags'] = $tags[$i];
                }else{
                    $update['tags_type'] = 2;
                }
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['created_at'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-完成".PHP_EOL;
    }

    /**
    * @desc    DaijinquanTag
    * @author  zhangheng
    */
    public function DaijinquanTag()
    {
        // $update['update_type'] = 0;
        // $updatecount = $list = Db::name('conversations')
        //     ->where('update_type',"<>",0)
        //     ->where('status',0)
        //     ->where('channel',1)
        //     ->where('created_at',">=","2024-12-01")
        //     ->update($update);
        // halt($updatecount);
        // 时间跟模板消息文本
        // 自动合并合并brand

        $t1       = microtime(true);
        $count = $list = Db::name('conversations')
            ->where('brand',"SheCurve")
            ->where('status',0)
            ->where('channel',1)
            ->where('tag_type',0)
            ->count();
        // halt($count);
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
                
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');

        for ($i = 0; $i <= $page; $i++){
            // $tags[$i];
            $list = Db::name('conversations')
                ->field('id,slug,brand')
                ->where('brand',"SheCurve")
                ->where('status',0)
                ->where('channel',1)
                ->where('tag_type',0)
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                $update = [];
                $slug = $v['slug'];
                //邮箱搜索
                $url = 'https://SheCurve.reamaze.io/api/v1/conversations/'.$slug;
                $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
                $tag = $return['tag_list'] ?? [];
                if (!empty($tag)) {
                    $v['tag_list'] = json_encode($tag, true);
                }else{
                    $v['tag_list'] = "";
                }
                $status = $return['status'];
                $emails = $return['author']['email'] ?? "";
                if ($status !== 0) {
                    echo '状态是'.$status;
                    $update['status'] = $status;
                    Db::name('conversations')->where('id',$v['id'])->update($update);
                    $executedCount++;
                    $num = $count - $executedCount;
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['slug'].',第' .$i.'页' . PHP_EOL;
                    continue;
                }
                //查看最新消息
                //邮箱搜索
                $url = 'https://SheCurve.reamaze.io/api/v1/conversations/'.$slug.'/messages';
                $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
                $messages = json_encode($return['messages'], true);
                $str = [
                    'voucher',
                    'coupon',
                    'gift card',
                    'partial refund',
                ];
                //是否包含
                for ($is = 0; $is < count($str); $is++){
                    if(strpos($messages, $str[$is]) !== false){
                        //修改标签
                        $return_con = $this->ModifyTagsinfo($v,"daijinquan");
                        if($return_con){
                            $update['tag_type'] = 1;
                            Db::name('conversations')->where('id',$v['id'])->update($update);
                            $executedCountsu++;
                        }
                        $executedCount++;
                        $num = $count - $executedCount;
                        echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['slug'].',第' .$i.'页' . PHP_EOL;
                        break;
                    }
                }
                $executedCount++;
                
                $update['tag_type'] = 2;
                $update['email'] = $emails;
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['slug'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
    * @desc    AddCategory
    * @author  zhangheng
    */
    public function AddCategory()
    {
        $t1       = microtime(true);
        $count = $list = Db::name('conversations')
            ->where('status',0)
            ->where('channel',1)
            ->where('category',"<>","")
            ->count();
        // halt($count);
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
                
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');

        for ($i = 0; $i <= $page; $i++){
            // $tags[$i];
            $list = Db::name('conversations')
                ->field('id,slug,brand,json')
                ->where('status',0)
                ->where('channel',1)
                ->where('category',"<>","")
                ->order('id desc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                $update = [];
                $return = json_decode($v['json'],true);
                $update['category'] = $return['category']['name'] ?? "";
                Db::name('conversations')->where('id',$v['id'])->update($update);
                $executedCount++;

                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['slug'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
    * @desc    FirstTag
    * @author  zhangheng
    */
    public function FirstTag()
    {
        $update['email'] = "";
        $update2 = Db::name('conversations')
            ->where('brand',"SheCurve")
            ->where('email',"=","support@shecurve.com")
            ->where('status',0)
            ->where('channel',1)
            ->update($update);
            echo PHP_EOL . "修改成功".$update2.PHP_EOL;

        $t1       = microtime(true);

        $count = $list = Db::name('conversations')
            ->where('brand',"SheCurve")
            ->where('email',"<>","")
            ->where('status',0)
            ->where('channel',1)
            ->where('tag_typea',0)
            ->count();
        echo PHP_EOL . "总计:" . $count . '条' . PHP_EOL;
        // halt($count);
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;

        for ($i = 0; $i <= $page; $i++){
            // $tags[$i];
            $list = Db::name('conversations')
                ->field('id,slug,brand,email')
                ->where('brand',"SheCurve")
                ->where('email',"<>","")
                ->where('status',0)
                ->where('channel',1)
                ->where('tag_typea',0)
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                $customer = Db::name('order_customer')->where('email',$v['email'])->find();
                $counts = 0;
                if($customer){
                    $counts = Db::name('order_achievement')
                        ->where('shop_id',17)
                        ->where('order_id',$customer['order_id'])
                        ->where('tags','like','%Master%')
                        ->where('payment_gateway_names',"shopify_payments")
                        ->count();
                        if($counts == 0){
                            $counts = Db::name('order_achievement')
                                ->where('shop_id',17)
                                ->where('order_id',$customer['order_id'])
                                ->where('tags','like','%paypal%')
                                ->where('payment_gateway_names',"paypal")
                                ->count();
                        }
                }
                if($counts > 0){
                    $return_con = $this->ModifyTagsinfo($v,"First");
                    if($return_con){
                        $update['tag_typea'] = 1;
                        $executedCountsu++;
                    }
                }
                $executedCount++;
                
                $update['tag_typea'] = 2;
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['slug'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
    * @desc    发送消息
    * @author  zhangheng
    */
    public function SendMessage()
    {
        // $update['update_type'] = 0;
        // $updatecount = $list = Db::name('conversations')
        //     ->where('update_type',"<>",0)
        //     ->where('status',0)
        //     ->where('channel',1)
        //     ->where('created_at',">=","2024-12-01")
        //     ->update($update);
        // halt($updatecount);
        // 时间跟模板消息文本
        // 自动合并合并brand

        $t1       = microtime(true);
        $count = $list = Db::name('conversations')
            ->where('brand',"SheCurve")
            ->where('message_count',1)
            ->where('update_type',0)
            ->where('status',0)
            ->where('channel',1)
            ->where('created_at',"<=","2025-01-10")
            ->where('created_at',">=","2025-01-01")
            ->count();
        // halt($count);
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 0; $i <= $page; $i++){
            // $tags[$i];
            $list = Db::name('conversations')
                ->where('brand',"SheCurve")
                ->where('message_count',1)
                ->where('update_type',0)
                ->where('status',0)
                ->where('channel',1)
                ->where('created_at',"<=","2025-01-10")
                ->where('created_at',">=","2025-01-01")
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                //修改标签
                $return_con = $this->SendMessageinfo($v);
                if($return_con){
                    $executedCountsu++;
                    $update['update_type'] = 1;
                }else{
                    $update['update_type'] = 2;
                }
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['slug'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
    * @desc    删除标签
    * @author  zhangheng
    */
    public function DeleteATap()
    {
        $tags = [
            0 => "AAAAA",
            1 => "BBBBB",
            2 => "CCCCC",
            3 => "DDDDD",
            4 => "EEEEE",
            5 => "FFFFF",
            6 => "GGGGG",
            7 => "HHHHH",
            8 => "JJJJJ",
            9 => "KKKKK",
            10 => "LLLLL"
        ];
        
        $t1       = microtime(true);
        // $pageSize = 600;
        //特殊标签
        foreach ($tags as $k => $tag) {
            $executedCount = 0;
            $executedCountsu = 0;
            $count = $list = Db::name('conversations')
                ->where('tags',$tag)
                ->count();
            $list = Db::name('conversations')
                ->where('tags',$tag)
                ->order('created_at asc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                //修改标签
                $return_con = $this->DeleteTagsinfo($v);
                if($return_con){
                    $executedCountsu++;
                    $update['tags_type'] = 4;
                    $update['tags'] = "";
                }else{
                    $update['tags_type'] = 5;
                }
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['created_at'].',' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function ModifyTagsinfo($v,$tags)
    {
        $brand = $v['brand'] ?? 'SheCurve';
        $tags = trim($tags);
        $slug = $v['slug'];
        $tag_list = $v['tag_list'] ?? "";
        if(empty($tag_list)){
            $tag_list = [$tags];
        }else{
            $tag_list = json_decode($tag_list,true);
            $tag_list = array_merge($tag_list,[$tags]);
        }
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug;
        $data['conversation']['tag_list'] = $tag_list;
        $return = HttpUtil::putUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        // halt($return);
        return true;
    }

    public function DeleteTagsinfo($v,$brand = 'SheCurve')
    {
        $slug = $v['slug'];
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug;
        $data['conversation']['tag_list'] = [];
        HttpUtil::putUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        return true;
    }

    public function SendMessageinfo($v)
    {
        $slug = $v['slug'];
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://SheCurve.reamaze.io/api/v1/conversations/'.$slug.'/messages';
        $data['message']['body'] = "Hello, this is Karen from the Shecurve Customer Support Team. We have received your email feedback and are currently looking into your order for urgent processing. You will receive our response and resolution within the next 72 hours. Thank you for your patience";
        $data['message']['visibility'] = 0;
        $data['message']['suppress_autoresolve'] = true;
        $data['message']['suppress_notifications'] = false;
        $return = HttpUtil::postUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        $this->ModifyTagsinfo($v,"replay");

        return true;
    }

    public function ViewMessage()
    {
        $slug = "return-order-number-617241";
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://SheCurve.reamaze.io/api/v1/conversations/'.$slug.'/messages';
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        halt($return['messages']);
        return true;
    }

    //争议统计
    public function DisputeStatistics()
    {
        $count = Db::name('order_dispute_afterpay')
            ->where('order_id',">",0)
            ->group('order_id')
            ->having('COUNT(*) > 1')
            ->count();
            // halt($count);
        echo PHP_EOL . "order_dispute_afterpay重复-开始操作" . PHP_EOL;
        if(!empty($count)){
            $duplicates = Db::name('order_dispute_afterpay')
                ->field('order_id, COUNT(*) as num_duplicates')
                ->where('order_id',">",0)
                ->group('order_id')
                ->having('COUNT(*) > 1')
                ->select()
                ->toArray();
            $executedCount = 0;
            foreach ($duplicates as $duplicate) {
                $keepId = Db::name('order_dispute_afterpay')
                    ->where('order_id', $duplicate['order_id'])
                    ->max('id');
                // 删除其他所有ID的记录
                Db::name('order_dispute_afterpay')
                    ->where('order_id', $duplicate['order_id'])
                    ->where('id', '<>', $keepId) // 排除要保留的记录
                    ->delete();
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "order_dispute_afterpay重复重复总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        } 

        $count = Db::name('order_dispute_api')
            ->where('order_id',">",0)
            ->group('order_id')
            ->having('COUNT(*) > 1')
            ->count();
            // halt($count);
        echo PHP_EOL . "order_dispute_api重复-开始操作" . PHP_EOL;
        if(!empty($count)){
            $duplicates = Db::name('order_dispute_api')
                ->field('order_id, COUNT(*) as num_duplicates')
                ->where('order_id',">",0)
                ->group('order_id')
                ->having('COUNT(*) > 1')
                ->select()
                ->toArray();
            $executedCount = 0;
            foreach ($duplicates as $duplicate) {
                $keepId = Db::name('order_dispute_api')
                    ->where('order_id', $duplicate['order_id'])
                    ->max('id');
                // 删除其他所有ID的记录
                Db::name('order_dispute_api')
                    ->where('order_id', $duplicate['order_id'])
                    ->where('id', '<>', $keepId) // 排除要保留的记录
                    ->delete();
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "order_dispute_api重复重复总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        } 

        $count = Db::name('order_dispute_airwallex')
            ->where('order_id',">",0)
            ->group('order_id')
            ->having('COUNT(*) > 1')
            ->count();
            // halt($count);
        echo PHP_EOL . "order_dispute_airwallex重复-开始操作" . PHP_EOL;
        if(!empty($count)){
            $duplicates = Db::name('order_dispute_airwallex')
                ->field('order_id, COUNT(*) as num_duplicates')
                ->where('order_id',">",0)
                ->group('order_id')
                ->having('COUNT(*) > 1')
                ->select()
                ->toArray();
            $executedCount = 0;
            foreach ($duplicates as $duplicate) {
                $keepId = Db::name('order_dispute_airwallex')
                    ->where('order_id', $duplicate['order_id'])
                    ->max('id');
                // 删除其他所有ID的记录
                Db::name('order_dispute_airwallex')
                    ->where('order_id', $duplicate['order_id'])
                    ->where('id', '<>', $keepId) // 排除要保留的记录
                    ->delete();
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "order_dispute_airwallex重复重复总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        } 
    }

    //未发货的客户order_customer_tag
    public function UnshippedCustomers()
    {
        $t1 = microtime(true);
        
        $where = [];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['fulfillment_status', '<>', "fulfilled"];
        $where[]  = ['shop_id', '=', 17];
        $where[]  = ['createtime', '>=', 1740499200];
        $where[]  = ['createtime', '<=', 1741190400];
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        echo PHP_EOL . "未发货的客户开始操作" . PHP_EOL;
        if(!empty($count)){
            $list = Db::name('order_achievement')
                ->field('order_id')
                ->where($where)
                ->select()
                ->toArray();
                $executedCount = 0;
                foreach ($list as $v) {
                    //查询客户
                    $customer = Db::name('order_customer')
                        ->where('order_id',$v['order_id'])
                        ->find();
                    if(!empty($customer)){
                        $insertData = [
                            'customer_id' => $customer['customer_id'],
                            'order_id' => $customer['order_id'],
                            'email' => $customer['email'],
                        ];
                        $order_customer_tag = Db::name('order_customer_tag')->where('order_id',$customer['order_id'])->find();
                        if(empty($order_customer_tag)){
                            Db::name('order_customer_tag')->insert($insertData);
                        }
                    }
                    $executedCount++;
                    $num = $count - $executedCount;
                    echo PHP_EOL . "未发货的客户总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
                }
                $t2 = microtime(true);
                echo PHP_EOL . "未发货的客户执行时间：" . ($t2 - $t1) . '秒' . PHP_EOL;
                return true;
        }
    }
    
    /**
    * @desc    给客户打标签
    * @author  zhangheng
    */
    public function LabelCustomers()
    {
        $count = Db::name('order_customer_tag')
            ->where('status',0)
            ->count();
        echo "给客户打标签".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

            $update = [];
            $update['status'] = 2;
            $customers = Db::name('order_customer_tag')
                ->field('customer_id')
                ->where('status',0)
                ->order('id asc')
                ->select()->toarray();
            
            $shop_id        = 17;
            $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
            foreach ($customers as $k=>$customer) {
                $customer_id        = $customer['customer_id'];
                //打标签
                $url = $shop_info['myshopify_domain'] ."/admin/api/2023-07/customers/".$customer_id.".json";
                $return = HttpUtil::getUrl($url,$shop_info);
                // halt($return);
                $tags        = $return['customer']['tags'] ?? "";
                $tags = !empty($tags) ? $tags . ",11-12meifa" : "11-12meifa";
                $data = [
                    'customer' => [
                        'id' => $customer_id,
                        'tags' => $tags,
                    ],
                ];
                // halt($url);
                $return = HttpUtil::PutUrl($url, $data, $shop_info);
                // halt($return);
                $update['status'] = 1;
                $executedCountsu++;
                $executedCount++;
                Db::name('order_customer_tag')
                    ->where('customer_id',$customer_id)
                    ->update($update);
                echo "总共".$count."条，客户：".$customer_id."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
    }

    
    //CustomersShippedLabel
    public function CustomersShippedLabel()
    {
        $t1 = microtime(true);
        // 1.退款订单中已发货的订单
        $where = [];
        // $where[]  = ['financial_status', 'in', ["partially_refunded", "refunded"]];

        // 2.退款订单中已发货的订单
        // $where[]  = ['disputeapi_type', '<>', ""];

        $where[]  = ['fulfillment_status', '=', "fulfilled"];
        $where[]  = ['createtime', '>=', 1730390400];
        $where[]  = ['createtime', '<=', 1743091200];
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        // halt($count);
        echo PHP_EOL . "已发货的".$count."开始操作" . PHP_EOL;
        if(!empty($count)){
            $pageSize = 500;
            $page     = ceil($count / $pageSize);
            $executedCount = 0;
            for ($i = 840; $i <= $page; $i++){
                $list = Db::name('order_achievement')
                    ->field('order_id,tracking_number,shop_id')
                    ->where($where)
                    ->order('id asc')
                    ->paginate([  
                        'list_rows' => $pageSize,
                        'page' => $i,
                    ])->toarray();
                foreach ($list['data'] as $v) {
                    if(strpos($v['tracking_number'],'4PX') !== false){
                        echo "4PX：".$v['tracking_number']."" . PHP_EOL;
                        continue;
                    }
                    if(strpos($v['tracking_number'],'SDH') !== false){
                        echo "SDH：".$v['tracking_number']."" . PHP_EOL;
                        continue;
                    }
                    $insert = [
                        'shop_id' => $v['shop_id'],
                        'order_id' => $v['order_id'],
                        'waybill_no' => $v['tracking_number'],
                    ];
                    $abnormal = Db::name('yuan_subsegment_abnormal')->where('order_id',$v['order_id'])->find();
                    if(!empty($abnormal)){
                        continue;
                    }
                    Db::name('yuan_subsegment_abnormal')->insert($insert);
                    $executedCount++;
                    $num = $count - $executedCount;
                    echo PHP_EOL . "已发货的客户总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第'.$i.'页' . PHP_EOL;
                }
            }
        }
        $t2 = microtime(true);
        echo PHP_EOL . "已发货的客户执行时间：" . ($t2 - $t1) . '秒' . PHP_EOL;
        return true;
    }
    
    /**
    * @desc    筛选查轨迹
    * @author  zhangheng
    */
    public function CustomersShipped()
    {
        // $update['status'] = 0;
        // $count = Db::name('yuan_subsegment_abnormal')
        //     // ->where('waybill_no',"like","%4PX%")
        //     // ->where('info',"like","%签收%")
        //     // ->where('trackContent',"货物电子信息已经收到")
        //     ->where('status',3)
        //     ->where('info',null)
        //     ->update($update);
        // halt($count);
        $count = Db::name('yuan_subsegment_abnormal')
            ->where('status',0)
            ->count();
        echo "筛选查轨迹".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $pageSize = 500;
        $page     = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $subsegment = Db::name('yuan_subsegment_abnormal')
                ->field('id,waybill_no,order_id,status')
                ->where('status',0)
                ->order('id asc')
                ->limit(500)
                ->select()->toarray();
            foreach ($subsegment as $k=>$v) {
                if($v['status'] !== 0 && $v['status'] !== 3){
                    echo "已执行过" . PHP_EOL;
                    continue;
                }
                $executedCount++;
    
                $number = $v['waybill_no'];
                // $result = $this->curlRequest('http://43.139.12.243:8082/getOrderTrackingNumber.htm', "documentCode=".$v['order_id']);
                // halt($result);
                $result = $this->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$number);
                $resultData = json_decode($result['result'], true);
                $trackingContent = $resultData[0]['data'][0] ?? "";
                // halt($trackingContent);
                if (!empty($trackingContent)) {
                    $update = [
                        'trackContent' => $trackingContent['trackContent'] ?? "无数据",
                        'info' => $trackingContent['businessStatus'] ?? "无数据",
                        'status' => 2,
                    ];
                    if($update['info'] == "签收"){
                        $update['status'] = 4;
                    }
                    Db::name('yuan_subsegment_abnormal')->where('id',$v['id'])->update($update);
                    $executedCountsu++;
                }else{
                    $update = [
                        'status' => 3,
                    ];
                    Db::name('yuan_subsegment_abnormal')->where('id',$v['id'])->update($update);
                }
                echo "当前第".$i."页，总共".$count."条，物流号：".$v['waybill_no']."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }

    public function CustomersShipped2()
    {
        $count = Db::name('yuan_subsegment_abnormal')
            ->where('status',"<=",3)
            ->where('created_at',"=",null)
            ->count();
        echo "筛选查轨迹".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $shops = Db::name('shops')->field('id,name')->select()->toarray();
        $shop_map = array_column($shops,'name','id');

        $subsegment = Db::name('yuan_subsegment_abnormal')
            ->where('status',"<=",3)
            ->where('created_at',"=",null)
            ->order('id asc')
            ->select()->toarray();
            
        foreach ($subsegment as $k=>$v) {
            $executedCount++;

            $order = Db::name('order_achievement')
                ->field('createtime,financial_status,disputeapi_type,disputeapi_status')
                ->where('order_id',$v['order_id'])
                ->find();
            
            $v['shop_id'] = $v['shop_id'] ?? 0;
            $shop_name = $shop_map[$v['shop_id']] ?? "";
            if($order['createtime']){
                $createtime = date("Y-m-d H:i:s",$order['createtime']);
            }
            $update = [
                'shop_name' => $shop_name,
                'created_at' => $createtime ?? "",
                'financial_status' => $order['financial_status'] ?? "",
                'disputeapi_type' => $order['disputeapi_type'] ?? "",
                'disputeapi_status' => $order['disputeapi_status'] ?? "",
            ];
            Db::name('yuan_subsegment_abnormal')->where('id',$v['id'])->update($update);
            $executedCountsu++;
            echo "总共".$count."条，客户：".$v['order_id']."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
        }
    }

    /**
    * @desc    给客户打标签
    * @author  zhangheng
    */
    public function WorkOrderLabel()
    {
        $count = Db::name('order_customer_tag')
            ->where('status',0)
            ->count();
        echo "给客户打标签".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

            $update = [];
            $update['status'] = 2;
            $customers = Db::name('order_customer_tag')
                ->field('customer_id,email')
                ->where('status',0)
                ->order('id asc')
                ->select()->toarray();
            
            $shop_id        = 17;
            $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
            foreach ($customers as $k=>$customer) {
                $where = [];
                $where[]  = ['status', '=', 0];
                $where[]  = ['channel', '=', 1];
                $where[] = ['json', 'like', '%' . $customer["email"] . '%'];
                $conversations = Db::name('conversations')
                    ->where($where)
                    ->find();
                //修改标签
                if(!empty($conversations)){
                    $this->ModifyTagsinfo($conversations,"Meifaaaaaa");
                    $executedCountsu++;
                }
                $update['status'] = 1;
                $executedCount++;
                Db::name('order_customer_tag')
                    ->where('customer_id',$customer['customer_id'])
                    ->update($update);
                echo "总共".$count."条，客户：".$customer['customer_id']."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
    }

    /**
    * @desc    给邮件平台打标签
    * @author  zhangheng
    */
    public function LabelTheEmailPlatform()
    {
        // $update = [];
        // $update['labelstatus'] = 0;
        // $updatecount = Db::name('order_customer_tag')
        //     ->where('labelstatus',"<>",0)
        //     ->update($update);
        // halt($updatecount);
        
        $t1       = microtime(true);
        $count = Db::name('order_customer_tag')
            ->where('labelstatus',0)
            ->count();
        // halt($count);
        // $pageSize = 600;
        //特殊标签
        $tags = "Meifaaaaaa";
        $executedCount = 0;
        $executedCountsu = 0;
        // $tags[$i];
        $list = Db::name('order_customer_tag')
            ->where('labelstatus',0)
            ->select()
            ->toArray();
        foreach ($list as $v){
            // halt($v);
            $wherec = [];
            $wherec[] = ['json', 'like', '%' . $v["email"] . '%'];
            $conversations = Db::name('conversations')->where($wherec)->find();
            //修改标签
            if(!empty($conversations)){
                // halt($conversations);
                $return_con = $this->ModifyTagsinfo($conversations,$tags);
            }else{
                $return_con = [];
            }
            if($return_con){
                $executedCountsu++;
                $update['labelstatus'] = 1;
            }else{
                $update['labelstatus'] = 2;
            }
            Db::name('order_customer_tag')->where('id',$v['id'])->update($update);

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].$v['email'].',' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //conversations找订单时间
    public function ConversationsFindOrderTime()
    {
        $t1 = microtime(true);
        $where = [];
        $where[]  = ['order_time', '=', ""];
        $where[]  = ['status', '=', 0];
        $where[]  = ['channel', '=', 1];
        $where[]  = ['created_at', '>=', "2024-11-01"];
        $count = Db::name('conversations')
            ->where($where)
            ->count();
        // halt($count);
        echo PHP_EOL . "conversations找订单时间" . PHP_EOL;
        if(!empty($count)){
            $pageSize = 10;
            $page     = ceil($count / $pageSize);
            $executedCount = 0;
            for ($i = 0; $i <= $page; $i++){
                $list = Db::name('conversations')
                    ->field('id,json,created_at')
                    ->where($where)
                    ->limit($pageSize)
                    ->order('created_at desc')
                    ->select()
                    ->toArray();
                    foreach ($list as $v) {
                        $created_at = $v['created_at'] ?? ""; 
                        $json = json_decode($v['json'],true);
                        $email = $json['author']['email'] ?? "";
                        if(!empty($email)){
                            //查询客户
                            $customer = Db::name('order_customer')
                                ->where('email',$email)
                                ->find();
                            if(!empty($customer)){
                                $created_at = getDateTime($customer['created_at']) ?? "";
                            }
                        }
                        if(empty($created_at)){
                            $created_at = $v['created_at']; 
                        }
                        $update = [];
                        $update['order_time'] = $created_at;
                        Db::name('conversations')->where('id',$v['id'])->update($update);

                        $executedCount++;
                        $num = $count - $executedCount;
                        echo PHP_EOL . "conversations找订单时间:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
                    }
                    $t2 = microtime(true);
            }
        }
    }

    
    /**
    * @desc    客服重新分配员工
    * @author  zhangheng
    */
    public function ReassignsEm()
    {
        $count = Db::name('conversations')
            ->where('status',0)
            ->where('channel',1)
            ->where('brand',"=","SheCurve")
            // ->where('created_at',">=","2025-02-01")
            ->where('assignee_email',"=","")
            // ->where('assignee_email',"=","waitingnowg@gmail.com")
            ->count();
        // halt($count);

        //特殊标签
        $tags = [
            0 => "1339161856@qq.com",
            1 => "goslingchan92@gmail.com",
            2 => "2426450501@qq.com",
            3 => "488721327@qq.com",
            4 => "2964696691@qq.com",
            5 => "939173652@qq.com",
        ];
        $page     = count($tags);
        $pageSize     = ceil($count / $page);
        
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 0; $i < $page; $i++){
            // halt($tags[$i]);
            $list = Db::name('conversations')
                ->field('id,brand,slug')
                ->where('status',0)
                ->where('channel',1)
                ->where('brand',"=","SheCurve")
                // ->where('created_at',">=","2025-02-01")
                ->where('assignee_email',"=","")
                // ->where('assignee_email',"=","waitingnowg@gmail.com")
                ->order('id asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                // halt($v);
                //修改标签
                $this->ReassignsEmployees($v,$tags[$i]);
                $update = [];
                $update['assignee_email'] = $tags[$i];
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-完成".PHP_EOL;
    }

    
    /**
    * @desc    回收分配
    * @author  zhangheng
    */
    public function RecyclingAndDistribution()
    {
        $count = Db::name('conversations')
            ->where('brand',"<>","SheCurve")
            ->where('status',0)
            ->where('channel',1)
            ->where('assignee_email',"<>","waitingnowg@gmail.com")
            ->count();
        // halt($count);
        $pageSize     = 100;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 0; $i < $page; $i++){
            $list = Db::name('conversations')
                ->field('id,brand,slug')
                ->where('brand',"<>","SheCurve")
                ->where('status',0)
                ->where('channel',1)
                ->where('assignee_email',"<>","waitingnowg@gmail.com")
                ->order('id asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                // halt($v);
                //修改标签
                $this->ReassignsEmployees($v,"waitingnowg@gmail.com");
                $update = [];
                $update['assignee_email'] = "waitingnowg@gmail.com";
                Db::name('conversations')->where('id',$v['id'])->update($update);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功修改'.$executedCountsu.'条，当前ID'.$v['id'].',第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-完成".PHP_EOL;
    }


    /**
    * 客服重新分配员工
    * @param array params
    */
    public function ReassignsEmployees($v,$email)
    {
        $brand = $v['brand'] ?? '';
        $slug = $v['slug'] ?? '';
        $assignee = [
            'email' => $email,
        ];
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug;
        $data['conversation']['assignee'] = $assignee;
        HttpUtil::putUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        echo PHP_EOL . "客服重新分配员工成功" .$slug. PHP_EOL;
    }

    
    //临时洗数据-----test
    public function TemporaryCheckTransactionNumber(){
        // $update = [
        //     'status' => 0,
        // ];
        // $count =  Db::name('test_copy1')
        //     ->where('status',"<>",1)
        //     ->update($update);
        //     halt($count);

        $count =  Db::name('test_copy1')
            ->where('status',0)
            ->count();
        // halt($count);

        $list =  Db::name('test_copy1')
            ->where('status',0)
            ->order('id','asc')
            ->select()
            ->toarray();
            // ->count();
            // halt($list);

        $executedCount = 0;
        foreach ($list as $k=>$v) {
            // 匹配规则
            $order = Db::name('order_transactions')
                ->where('authorization',$v['email'])
                ->find();
            if(!empty($order)){
                $order_achievement = Db::name('order_achievement')->where('order_id',$order['order_id'])->find();
                $update = [
                    'order_id'=>$order_achievement['tracking_number'] ?? 0,
                    'status'=>1,
                ];
                Db::name('test_copy1')->where('id',$v['id'])->update($update);
            }else{
                $update = [
                    'status'=>2,
                ];
                Db::name('test_copy1')->where('id',$v['id'])->update($update);
            }
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }

    /**
    * @desc    shopify创建退款
    * @author  zhangheng
    */
    public function ShopifyCreatesRefunds()
    {
        $order_id = '6735209890162';
        $shop_id        = 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();

        // $version        = Config('Logisticskey.shopify.api_versoin');
        // $url            = $shop_info['myshopify_domain'].$version . "/orders/".$order_id."/transactions.json";
        // $return = HttpUtil::getUrl($url, $shop_info);
        // halt($return);

        $url = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id."/refunds.json";
        $transactions = [
            0 => [
                'amount' => 30,
                'gateway' => "cash",
                'kind' => "refund",
            ],
        ];
        $shipping = [
            'full_refund' => true,
        ];
        $data = [
            'refund' => [
                'currency' => "CAD",
                'notify' => true,
                'note' => "",
                'transactions' => $transactions,
                'shipping' => $shipping,
            ],
        ];
        // halt($data);
        $return = HttpUtil::PostUrl($url, $data, $shop_info);
        halt($return);
    }
    
    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function test_order()
    {
        $id = '82371';
        $order_webhooks = db::name('order_webhooks')->where('id',$id)->find();
        $params = json_decode($order_webhooks['json'],true);
        $ApiOrderLogic = new ApiOrderLogic();
        $ApiOrderLogic->SynchronizeModifications($params,$order_webhooks['shop_id']);
    }

    /**
    * @desc    更新状态以及附加数据
    * @author  zhangheng
    */
    public function UpdateStatusdisputeapi()
    {
        $t1       = microtime(true);
        $shop_id = 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');

        $count = 200;
        $dispute_id = "";
        for ($i = 1; $i <= $count; $i++){
            $url = $shop_info['myshopify_domain'].$version . "/shopify_payments/disputes.json";
            if(!empty($dispute_id)){
                $url = $url . '?last_id=' . $dispute_id;
            }
            echo PHP_EOL . "url:".$url . PHP_EOL;
            $return = HttpUtil::getUrl($url, $shop_info);
            $dispute_id = $this->dispute_id($return,$dispute_id);
            echo PHP_EOL . "第" . $i . "页,争议id".$dispute_id . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function dispute_id($return,$dispute_id)
    {
        $shop_id = 17;
        $disputes = $return['disputes'] ?? [];
        if (is_array($disputes) && !empty($disputes)) {
            date_default_timezone_set('Asia/Shanghai');
            foreach ($disputes as $dispute) {
                $order_dispute_api = Db::name('order_dispute_api')->where('dispute_id',$dispute['id'])->find();
                $arr = [];
                $arr['order_id'] = $dispute['order_id'] ?? "";
                $arr['type'] = $dispute['type'] ?? "";
                $arr['amount'] = $dispute['amount'] ?? "";
                $arr['currency'] = $dispute['currency'] ?? "";
                $arr['reason'] = $dispute['reason'] ?? "";
                $arr['network_reason_code'] = $dispute['network_reason_code'] ?? "";
                $arr['status'] = $dispute['status'] ?? "";
                $arr['evidence_due_by'] = $dispute['evidence_due_by'] ?? "";
                $arr['initiated_at'] = $dispute['initiated_at'] ?? "";
                $arr['json'] = json_encode($dispute, true);
                $arr['shop_id'] = $shop_id;
                if ($order_dispute_api) {
                    Db::name('order_dispute_api')->where('dispute_id',$dispute['id'])->update($arr);
                    echo PHP_EOL . "更新成功".$dispute['id'] . PHP_EOL;
                } else {
                    $arr['dispute_id'] = $dispute['id'] ?? "";
                    Db::name('order_dispute_api')->insert($arr);
                    echo PHP_EOL . "新增成功".$dispute['id'] . PHP_EOL;
                }
                if(!empty($dispute['id'])){
                    $dispute_id = $dispute['id'];
                }
            }
        }
        return $dispute_id;
    }


    /**
    * @desc    product_seller_sku表每天更新sku销量
    * @author  zhangheng
    */
    public function UpdateSkuSales()
    {
        $t1       = microtime(true);
        $count = Db::name('product_seller_sku')
            ->where('spu_90days',">",0)
            // ->where('seller_sku',"=",'bra10-skin-36D')
            ->count();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('product_seller_sku')
                ->field('
                        id,
                        seller_sku
                    ')
                ->where('spu_90days',">",0)
                // ->where('seller_sku',"=",'bra10-skin-36D')
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            foreach ($list['data'] as $v){
                $executedCount++;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '当前第' .$i.'页' . PHP_EOL;
                $where = [];
                $where[]  = ['a.new_sku', '=', $v['seller_sku']]; 
                $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

                //90天销量
                $where2 = [];
                $where2[]  = ['c.createtime', '>=', time() - 3600*24*90];
                $where2[]  = ['c.createtime', '<=', time()];
                $lists = Db::name('order_skuinfo')
                    ->field('
                        sum(a.realcount) as sku_90days,
                        a.new_sku as sku
                    ')
                    ->alias('a')
                    ->join('qu_order c','a.order_id = c.order_id', 'left')
                    ->where($where)
                    ->where($where2)
                    ->order('count desc')
                    ->select()->toarray();
                $sku_90days = $lists[0]['sku_90days'] ?? 0;
                if($sku_90days == 0){
                    $update = [
                        'sku_90days'=>0,
                        'sku_30days'=>0,
                        'sku_15days'=>0,
                        'sku_7days'=>0,
                        'sku_3days'=>0,
                        'sku_1days'=>0,
                    ];
                    Db::name('product_seller_sku')
                        ->where('id',$v['id'])
                        ->update($update);
                    continue;
                }
// halt($sku_90days);
                //30天销量
                $where2 = [];
                $where2[]  = ['c.createtime', '>=', time() - 3600*24*30];
                $where2[]  = ['c.createtime', '<=', time()];
                $lists = Db::name('order_skuinfo')
                    ->field('
                        sum(a.realcount) as sku_30days,
                        a.new_sku as sku
                    ')
                    ->alias('a')
                    ->join('qu_order c','a.order_id = c.order_id', 'left')
                    ->where($where)
                    ->where($where2)
                    ->order('count desc')
                    ->select()->toarray();
                $sku_30days = $lists[0]['sku_30days'] ?? 0;
                if($sku_30days == 0){
                    $update = [
                        'sku_90days'=>$sku_90days,
                        'sku_30days'=>0,
                        'sku_15days'=>0,
                        'sku_7days'=>0,
                        'sku_3days'=>0,
                        'sku_1days'=>0,
                    ];
                    Db::name('product_seller_sku')
                        ->where('id',$v['id'])
                        ->update($update);
                    continue;
                }

                //15天销量
                $where2 = [];
                $where2[]  = ['c.createtime', '>=', time() - 3600*24*15];
                $where2[]  = ['c.createtime', '<=', time()];
                $lists = Db::name('order_skuinfo')
                    ->field('
                        sum(a.realcount) as sku_15days,
                        a.new_sku as sku
                    ')
                    ->alias('a')
                    ->join('qu_order c','a.order_id = c.order_id', 'left')
                    ->where($where)
                    ->where($where2)
                    ->order('count desc')
                    ->select()->toarray();
                $sku_15days = $lists[0]['sku_15days'] ?? 0;
                if($sku_15days == 0){
                    $update = [
                        'sku_90days'=>$sku_90days,
                        'sku_30days'=>$sku_30days,
                        'sku_15days'=>0,
                        'sku_7days'=>0,
                        'sku_3days'=>0,
                        'sku_1days'=>0,
                    ];
                    Db::name('product_seller_sku')
                        ->where('id',$v['id'])
                        ->update($update);
                    continue;
                }

                //7天销量
                $where2 = [];
                $where2[]  = ['c.createtime', '>=', time() - 3600*24*7];
                $where2[]  = ['c.createtime', '<=', time()];
                $lists = Db::name('order_skuinfo')
                    ->field('
                        sum(a.realcount) as sku_7days,
                        a.new_sku as sku
                    ')
                    ->alias('a')
                    ->join('qu_order c','a.order_id = c.order_id', 'left')
                    ->where($where)
                    ->where($where2)
                    ->order('count desc')
                    ->select()->toarray();
                $sku_7days = $lists[0]['sku_7days'] ?? 0;
                if($sku_7days == 0){
                    $update = [
                        'sku_90days'=>$sku_90days,
                        'sku_30days'=>$sku_30days,
                        'sku_15days'=>$sku_15days,
                        'sku_7days'=>0,
                        'sku_3days'=>0,
                        'sku_1days'=>0,
                    ];
                    Db::name('product_seller_sku')
                        ->where('id',$v['id'])
                        ->update($update);
                    continue;
                }

                //3天销量
                $where2 = [];
                $where2[]  = ['c.createtime', '>=', time() - 3600*24*3];
                $where2[]  = ['c.createtime', '<=', time()];
                $lists = Db::name('order_skuinfo')
                    ->field('
                        sum(a.realcount) as sku_3days,
                        a.new_sku as sku
                    ')
                    ->alias('a')
                    ->join('qu_order c','a.order_id = c.order_id', 'left')
                    ->where($where)
                    ->where($where2)
                    ->order('count desc')
                    ->select()->toarray();
                $sku_3days = $lists[0]['sku_3days'] ?? 0;
                if($sku_3days == 0){
                    $update = [
                        'sku_90days'=>$sku_90days,
                        'sku_30days'=>$sku_30days,
                        'sku_15days'=>$sku_15days,
                        'sku_7days'=>$sku_7days,
                        'sku_3days'=>0,
                        'sku_1days'=>0,
                    ];
                    Db::name('product_seller_sku')
                        ->where('id',$v['id'])
                        ->update($update);
                    continue;
                }

                //1天销量
                $where2 = [];
                $where2[]  = ['c.createtime', '>=', time() - 3600*24*1];
                $where2[]  = ['c.createtime', '<=', time()];
                $lists = Db::name('order_skuinfo')
                    ->field('
                        sum(a.realcount) as sku_1days,
                        a.new_sku as sku
                    ')
                    ->alias('a')
                    ->join('qu_order c','a.order_id = c.order_id', 'left')
                    ->where($where)
                    ->where($where2)
                    ->order('count desc')
                    ->select()->toarray();
                $sku_1days = $lists[0]['sku_1days'] ?? 0;
                $update = [
                    'sku_90days'=>$sku_90days,
                    'sku_30days'=>$sku_30days,
                    'sku_15days'=>$sku_15days,
                    'sku_7days'=>$sku_7days,
                    'sku_3days'=>$sku_3days,
                    'sku_1days'=>$sku_1days,
                ];
                if($sku_90days > 0){
                    $executedCountsu++;
                }
                Db::name('product_seller_sku')
                    ->where('id',$v['id'])
                    ->update($update);
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . '成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
    * @desc    product_seller_sku表每天更新sku销量
    * @author  zhangheng
    */
    public function UpdateSpuSales()
    {
        $t1       = microtime(true);
        $count = Db::name('product_seller_sku')
            ->group('spu')
            ->count();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('product_seller_sku')
                ->field('
                        id,
                        spu
                    ')
                ->group('spu')
                ->order('id desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
            
            foreach ($list['data'] as $v){
                $where = [];
                $where[]  = ['a.spu', '=', $v['spu']]; 
                $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

                //90天销量
                $where2 = [];
                $where2[]  = ['c.createtime', '>=', time() - 3600*24*90];
                $where2[]  = ['c.createtime', '<=', time()];
                $lists = Db::name('order_skuinfo')
                    ->field('
                        sum(a.realcount) as sku_90days,
                        a.spu as spu
                    ')
                    ->alias('a')
                    ->join('qu_order c','a.order_id = c.order_id', 'left')
                    ->where($where)
                    ->where($where2)
                    ->order('count desc')
                    ->select()->toarray();
                $spu_90days = $lists[0]['sku_90days'] ?? 0;
                $update = [
                    'spu_90days'=>$spu_90days,
                ];
                if($spu_90days > 0){
                    $executedCountsu++;
                }
                Db::name('product_seller_sku')
                    ->where('spu',$v['spu'])
                    ->update($update);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条，当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }


    /**
     * @date    2024-10-19
     */
    public function get_airwallex_list(){
        $list = [
            'shecurve',//1000多
            'woobilly',//980
            'lilylove',//400
            'kisslove',//28
            'shecurvede',//172
            'elizabathbra'//9
        ];
        foreach($list as $k=>$v){
            $this->get_airwallex_list2($v);
            echo $v."完成";
        }
    }
    /**
     * @date    2024-10-19
     */
    public function get_airwallex_list2($name){
        // $page_after = "YWZ0ZXI9ZHN0X2hrcGRxdG5sbWd6ZzVyOWg5bnY=";//shecurve
        $page_after = "";
        $token       = $this->get_token($name);
        $basic_url   = Config('Logisticskey.airwallex.basic_url');
        $login_url   = Config('Logisticskey.airwallex.dispute_url');
        $url         = $basic_url.$login_url."?size=50";
        if($page_after){
            $url = $url.'&page='.$page_after;
        }
        $key         = 'airwallex_token'.$name;
        $info        = HttpUtil::getUrlshopline($url,['app_secret'=>$token]);
        if(isset($info['code']) && $info['code']=='unauthorized'){
            Cache::store('redis')->delete($key);
            $token       = $this->get_token($name);
            $info        = HttpUtil::getUrlshopline($url,['app_secret'=>$token]);
        }
        // halt($info);
        // 数据入库;
        $list  = $info['items']??[];
        $page_before  = $info['page_before']??'';
        $page_after  = $info['page_after']??'';
        if(!$list)  return  '暂无数据!';
        $arr = [];
        $count = 0;
        foreach($list as $v){
            $arr = self::insert_airwallex_info($v);
            $arr['api_type'] = $name;
            $new_arr = Db::name('order_dispute_airwallex')->where('airwallex_id',$v['id'])->find();
            $count++;
            if(!$new_arr){
                echo PHP_EOL . $name ."店铺：". $count . "插入成功!" . PHP_EOL;
                Db::name('order_dispute_airwallex')->insert($arr);
            }else{
                echo PHP_EOL . $name ."店铺：". $count . "修改成功!" . PHP_EOL;
                Db::name('order_dispute_airwallex')->where('airwallex_id',$v['id'])->update($arr);
            }
        }
        
        echo "page_before码".$page_before;
        echo "page_after码".$page_after;
    }
    
    /**
     * @desc    空中云慧数据获取
     * @author  luckyXiong
     * @date    2024-10-19
     */
    private function insert_airwallex_info($info=[]){
        $merchant_order_id = $info['merchant_order_id'];
        // $order_id = Db::name('order_transactions')->where(['payment_id'=>$merchant_order_id])->value('order_id');
        // $orderId  = $order_id ?:'';
        $airwallex_status = Config('Logisticskey.airwallex_status');
        $status_cn = $airwallex_status[$info['status']]??'';
        $data = [
            'airwallex_id'       =>$info['id'],
            // 'order_id'           =>$orderId,
            'payment_order_id'   =>$merchant_order_id,
            'payment_intent_id'  =>$info['payment_intent_id'],
            'payment_attempt_id' =>$info['payment_attempt_id'],
            'payment_method_type'=>$info['payment_method_type'],
            'stage'              =>$info['stage'],
            'status'             =>$info['status'],
            'reason'             =>$info['reason']['description'] ?? '',
            'status_cn'          =>$status_cn,
            'due_at'             =>$info['due_at']     ? date("Y-m-d H:i:s", strtotime($info['due_at'])) : '',
            'created_at'         =>$info['created_at'] ? date("Y-m-d H:i:s", strtotime($info['created_at'])) : '',
            'updated_at'         =>$info['updated_at'] ? date("Y-m-d H:i:s", strtotime($info['updated_at'])) : '',
        ];
        return $data;
    }
    //云汇详情
    public function airwallex_transactions_info($params=[]){
            $name = 'shecurve';
            $key         = 'airwallex_token'.$name;
            // Cache::store('redis')->delete($key);
            $token       = $this->get_token($name);
            $page_after  = $params['page_after']??'';
$url = 'https://api.airwallex.com/api/v1/issuing/transactions/r3p2B2l6vlJVUZcPiaCix60T6';
            if($page_after){
            $url = $url.'?page='.$page_after;
            }
            $info        = HttpUtil::getUrlshopline($url,['app_secret'=>$token]);
            halt($info);
    }
    /**
     * @desc    空中云慧数据获取
     * @author  luckyXiong
     * @date    2024-10-19
     */
    public function get_token($name){
        $key         = 'airwallex_token'.$name;
        $token       = Cache::store('redis')->get($key);
        if(empty($token)){
            $merchantId  = Config('Logisticskey.airwallex.'.$name.'.merchantId');
            $merchantKey = Config('Logisticskey.airwallex.'.$name.'.merchantKey');
            $basic_url   = Config('Logisticskey.airwallex.basic_url');
            $login_url   = Config('Logisticskey.airwallex.login_url');
            $url         = $basic_url.$login_url;
            $data        = [
                'merchantId' =>$merchantId,
                'merchantKey'=>$merchantKey,
            ];
            $response  =  HttpUtil::getAirwallexUrlToken($url,$data);
            $token     =  $response['token']??'';
            $expire    =  strtotime($response['expires_at']);
            Cache::store('redis')->set($key, $token,$expire-3);
        }
        return  $token;

    }

    /**
    * @author  zhangheng
    */
    public function CustomerServiceDaily()
    {
        $date = "";
        if(!empty($date)){
            
        }else{
            // 10天
            for($num = 0; $num <= 120; $num++){//抓取历史数据
                $start_time = date('Y-m-d', time() - 15*2400 - 3600*24*$num);
                $end_time = date('Y-m-d', time() - 15*2400 + 86400 - 3600*24*$num);
                $this->CustomerServiceDaily_info($start_time,$end_time);
                echo PHP_EOL . '完成更新,日期'.$start_time . PHP_EOL;
            }
        }
    }

    /**
    * @author  zhangheng
    */
    public function CustomerServiceDaily_info($start_time,$end_time)
    {
        // status 4 存档
        // status 8 聊天机器人解决
        // status 3 垃圾邮件
        // status 5 暂停
        $reamaze = [];
        //未解决
        $where = [];
        $where[] = ['created_at',"<",$end_time];
        $where[] = ['created_at',">=",$start_time];
        $where[] = ['channel',"=",1];
        $where2 = [];
        $where2[] = ['status',"=",0];
        $noreceived = DB::name('conversations')
            ->field('brand,count(*) as count')
            ->where($where)
            ->where($where2)
            ->group('brand')
            ->select()->toarray();
        // halt($noreceived);
        $reamaze['noreceived'] = 0;
        foreach($noreceived as $k=>$v){
            if($v['brand'] == "SheCurve"){
                $reamaze['noreceived_SheCurve'] = $v['count'] ?? 0;
                $reamaze['noreceived'] += $v['count'] ?? 0;
            }
            if($v['brand'] == "4304ef"){
                $reamaze['noreceived_Woobilly'] = $v['count'] ?? 0;
                $reamaze['noreceived'] += $v['count'] ?? 0;
            }
            if($v['brand'] == "LilyLove"){
                $reamaze['noreceived_LilyLove'] = $v['count'] ?? 0;
                $reamaze['noreceived'] += $v['count'] ?? 0;
            }
        }

        //当日新增
        $where2 = [];
        $where2[] = ['status','in',[0,2,6,3,4,5,8]];
        $add = DB::name('conversations')
            ->field('brand,count(*) as count')
            ->where($where)
            ->where($where2)
            ->group('brand')
            ->select()->toarray();
            // halt($add);
        $reamaze['add'] = 0;
        foreach($add as $k=>$v){
            if($v['brand'] == "SheCurve"){
                $reamaze['add_SheCurve'] = $v['count'] ?? 0;
                $reamaze['add'] += $v['count'] ?? 0;
            }
            if($v['brand'] == "4304ef"){
                $reamaze['add_Woobilly'] = $v['count'] ?? 0;
                $reamaze['add'] += $v['count'] ?? 0;
            }
            if($v['brand'] == "LilyLove"){
                $reamaze['add_LilyLove'] = $v['count'] ?? 0;
                $reamaze['add'] += $v['count'] ?? 0;
            }
        }
        //处理
        $where2 = [];
        $where2[] = ['status','in',[2,3,4,5,8]];
        $handle = DB::name('conversations')
            ->field('brand,count(*) as count')
            ->where($where)
            ->where($where2)
            ->group('brand')
            ->select()->toarray();
        $reamaze['handle'] = 0;
        foreach($handle as $k=>$v){
            if($v['brand'] == "SheCurve"){
                $reamaze['handle_SheCurve'] = $v['count'] ?? 0;
                $reamaze['handle'] += $v['count'] ?? 0;
            }
            if($v['brand'] == "4304ef"){
                $reamaze['handle_Woobilly'] = $v['count'] ?? 0;
                $reamaze['handle'] += $v['count'] ?? 0;
            }
            if($v['brand'] == "LilyLove"){
                $reamaze['handle_LilyLove'] = $v['count'] ?? 0;
                $reamaze['handle'] += $v['count'] ?? 0;
            }
        }
        $reamaze['create_time'] = $start_time;
        $reamaze['timedate'] = strtotime($start_time);
        if(DB::name('report_reamaze')->where(['create_time'=>$start_time])->find()){
            DB::name('report_reamaze')->where(['create_time'=>$start_time])->update($reamaze);
        }else{
            DB::name('report_reamaze')->insert($reamaze);
        }
        return true;
    }
    
    /**
    * 退款列表新增字段
    * @author  zhangheng
    */
    public function refundListAddfield()
    {
        $where = [];
        $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',time() - 3600*24)];
        $count = DB::name('customer_refunds')
            ->where($where)
            // ->group('order_id')
            ->count();
            // halt($count);
        echo PHP_EOL . "退款列表新增字段".$count."条" . PHP_EOL;
        if(!empty($count)){
            $admin_users     = Db::name('system_admin')->field('id,username')->select()->toArray();
            $admin_users_map = array_column($admin_users,null,'id');
            $shop_names     = Db::name('shops')->field('id,name,domain')->select()->toArray();
            $shop_names_map = array_column($shop_names,null,'id');

            $pageSize = 500; // 每500条记录读取一次
            $page     = ceil($count / $pageSize);
            $executedCount = 0;
            for ($i = 1; $i <= $page; $i++){
                $list = DB::name('customer_refunds')
                    ->field('id,order_id,refund_status,refund_payment,payment,operate_id,shop_id,create_time,ProductSku')
                    ->where($where)
                    ->order('id desc')
                    ->paginate([  
                        'list_rows' => $pageSize,
                        'page' => $i,
                    ])->toarray();
                foreach ($list['data'] as $v) {
                    //skus
                    if(!empty($v['ProductSku'])){
                        $order_info = db::name('order_info')->field('sku')->where('id',"in",$v['ProductSku'])->select()->toarray();
                        $skus = array_column($order_info,'sku');
                        $skus = implode(',',$skus);
                    }
                    $skus = $skus ?? "";
                    //邮箱
                    $order_customer = Db::name('order_customer')->field('email')->where('order_id',$v['order_id'])->find();
                    $email  = $order_customer['email'] ?? "";

                    //会话数量
                    if($email){
                        $conversations = Db::name('conversations')
                            ->where('email',$email)
                            ->count();
                    }
                    $conversations  = $conversations ?? 0;

                    //加支付渠道跟物流状态
                    $order_achievement = Db::name('order_achievement')->field('payment_gateway_names,fulfillment_status,createtime')->where('order_id',$v['order_id'])->find();
                    $payment_gateway_names  = $order_achievement['payment_gateway_names'] ?? "";
                    $fulfillment_status  = $order_achievement['fulfillment_status'] ?? "";
                    $createtime  = $order_achievement['createtime'] ?? "";
                    if(!empty($createtime)){
                        $createtime = date('Y-m-d',$createtime);
                    }
                    if(!empty($v['create_time'])){
                        $create_time = date('Y-m-d',strtotime($v['create_time']));
                    }
                    if($fulfillment_status == 'fulfilled'){
                        $fulfillment_status = '已发货';
                    }else{
                        $fulfillment_status = '未发货';
                    }
                    
                    $refund_rate              = '';
                    if($v['refund_status']=='2' && $v['refund_payment'] > 0 && $v['payment'] > 0 ){
                        $refund_rate = getRes((float)$v['refund_payment']/(float)$v['payment']*100).'%';
                    }

                    $admin_users_info       = $admin_users_map[$v['operate_id']]??'';
                    $operater   = $admin_users_info['username']??'';
                    $shopNames                = $shop_names_map[$v['shop_id']]??[];
                    $shop_name                = $shopNames['name']??'';
                    
                    $update = [
                        'skus'              => $skus,
                        'email'              => $email,
                        'conversations'      => $conversations,
                        'payment_gateway_names' => $payment_gateway_names,
                        'fulfillment_status' => $fulfillment_status,
                        'operater' => $operater,
                        'shop_name' => $shop_name,
                        'createtime' => $createtime,
                        'create_time' => $create_time,
                        'refund_rate' => $refund_rate
                    ];
                    // halt($update);
                    Db::name('customer_refunds')->where('id',$v['id'])->update($update);

                    $executedCount++;
                    $num = $count - $executedCount;
                    echo PHP_EOL . "退款列表新增字段:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '当前id:' . $v['id'] . '条,当前页数'.$i . PHP_EOL;
                }
            }
        }
        echo "完成". PHP_EOL;
    }

    /**
    * 退款列表新增字段
    * @author  zhangheng
    */
    public function refundListAddfieldinfo()
    {
        $where = [];
        $where[]  = ['info_status', '=', 0];
        $where[]  = ['createtime', '>', 0];
        $valuesome = [21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44];
        $where[] = ['ReasonForRefund', 'in', $valuesome];

        // $where[]  = ['info_status', '<>', 0];
        // $update = DB::name('customer_refunds')
        //     ->where($where)
        //     ->update([
        //         'info_status' => 0
        //     ]);
        // halt($update);

        $count = DB::name('customer_refunds')
            ->where($where)
            ->count();
            // halt($count);
        echo PHP_EOL . "退款列表详情".$count."条" . PHP_EOL;
        if(!empty($count)){
            $pageSize = 500; // 每500条记录读取一次
            $page     = ceil($count / $pageSize);
            $executedCount = 0;
            for ($i = 1; $i <= $page; $i++){
                $list = DB::name('customer_refunds')
                    ->where($where)
                    ->order('id desc')
                    ->limit($pageSize)
                    ->select()
                    ->toArray();
                foreach ($list as $v) {
                    $skus = $v['skus'] ?? '';
                    if (strpos($skus, ',') !== false) { 
                        $skus = explode(',', $skus);
                        foreach ($skus as $skuk=>$skuy) { 
                            $sku = trim($skuy);
                            $this->refunds_info_insert($v,$sku);
                        }
                    }else{
                        $this->refunds_info_insert($v);
                    }
                    Db::name('customer_refunds')->where('id',$v['id'])->update([
                        'info_status' => 1,
                    ]);
                    $executedCount++;
                    $num = $count - $executedCount;
                    echo PHP_EOL . "退款列表详情:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '当前id:' . $v['id'] . '条,剩余'.$num . PHP_EOL;
                }
            }
        }
        echo "完成". PHP_EOL;
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function refunds_info_insert($v,$sku='')
    {
        if(!empty($sku)){
            $v['skus'] = $sku;
        }
        $order_info = Db::name('order_info')
            ->where('order_id',$v['order_id'])
            ->where('sku',$v['skus'])
            ->find();
        if (empty($order_info)) {
            $order_info = Db::name('order_info')
                ->where('order_id',$v['order_id'])
                ->find();
        }
        $sku_id = $order_info['variant_id'] ?? "";
        $order_skuinfo = Db::name('order_skuinfo')
            ->where('order_id',$v['order_id'])
            ->where('sku_id',$sku_id)
            ->select()->toarray();
        foreach ($order_skuinfo as $ks=>$vs) {
            $update = [
                'order_id' => $v['order_id'],
                'order_number' => $v['order_number'],
                'shop_id' => $v['shop_id'],
                'create_time' => $v['create_time'],
                'createtime' => $v['createtime'],
                'ReasonForRefund' => $v['ReasonForRefund'],
                'num' => $vs['realcount'] ?? 0,
                'skus' => $vs['new_sku'] ?? "",
                'spu' => $vs['spu'] ?? "",
            ];
            $refunds_info = Db::name('customer_refunds_info')
                ->where('order_id',$update['order_id'])
                ->where('skus',$update['skus'])
                ->find();
            if ($refunds_info) { 
                Db::name('customer_refunds_info')
                    ->where('order_id',$update['order_id'])
                    ->where('skus',$update['skus'])
                    ->update($update);
            }else{ 
                Db::name('customer_refunds_info')->insert($update);
            }
        }
        return true;
    }
    

    /**
    * @author  zhangheng
    */
    public function OrderCustomerBackup()
    {
        $t1       = microtime(true);

        $old_shop_id = 22;
        $new_shop_id = 19;
        $where = [];
        $where[] = ['shop_id',"=",$old_shop_id];
        $where[] = ['BackupStatus',"=",0];
        $count = Db::name('order_customer')
            ->where($where)
            ->count();
        // halt($count);
        if($count == 0){
            echo "没有需要备份的数据";die;
        }
        $shop_info = Db::name('shops')->where('id', $old_shop_id)->find();
        $shop_info_new = Db::name('shops')->where('id', $new_shop_id)->find();

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){   
            $order_customer = Db::name('order_customer')
                ->field('id,order_id,customer_id')
                ->where($where)
                ->limit($pageSize)
                ->order('id desc')
                ->find();
            $customer_id = $order_customer['customer_id'] ?? 0;
            if($customer_id == 0){
                echo "没有customer_id" . PHP_EOL;
                continue;
            }
            //订单customers
            $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/customers/".$customer_id.".json";
            $return = HttpUtil::getUrl($url,$shop_info);
            if (isset($return['errors']) && !empty($return['errors'])) {
                echo "查询客户接口错误" . PHP_EOL;
                continue;
            }
            //先新增客户
            unset($return['customer']['id']);
            foreach ($return['customer']['addresses'] as $k=>$v) {
                unset($return['customer']['addresses'][$k]['id']);
                unset($return['customer']['addresses'][$k]['customer_id']);
            }
            $customer_new = $return['customer'] ?? [];
            $url = $shop_info_new['myshopify_domain'] . "/admin/api/2023-07/customers.json";
            $return = HttpUtil::PostUrl($url,$return, $shop_info_new);
            $return = json_decode($return, true);
            if (isset($return['errors']) && !empty($return['errors'])) {
                echo "新增客户接口错误" . PHP_EOL;
                // continue;
            }else{
                echo "新增客户成功".$return['customer']['id'].PHP_EOL;
            }

            $update['BackupStatus'] = 1;
            Db::name('order_customer')->where('id',$order_customer['id'])->update($update);
            //新增订单
            $order_id = $order_customer['order_id'] ?? 0;
            if($order_id == 0){
                echo "没有order_id" . PHP_EOL;
                continue;
            }
            $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id.".json";
            $return = HttpUtil::getUrl($url,$shop_info);
            if (isset($return['errors']) && !empty($return['errors'])) {
                echo "查询订单接口错误" . PHP_EOL;
                continue;
            }
            $url = $shop_info_new['myshopify_domain'] . "/admin/api/2023-07/orders.json";
            unset($return['order']['id']);
            $returnnew = [];
            $returnnew['order']['line_items'] = $return['order']['line_items'] ?? [];
            $returnnew['order']['customer'] = $customer_new;
            $returnnew['order']['financial_status'] = $return['order']['financial_status'] ?? "";
            $returnnew['order']['fulfillment_status'] = $return['order']['fulfillment_status'] ?? "";
            if(empty($returnnew['order']['fulfillment_status'])){
                unset($returnnew['order']['fulfillment_status']);
            }else{
                echo "物流状态".$returnnew['order']['fulfillment_status'];
            }
            $return = HttpUtil::PostUrl($url,$returnnew, $shop_info_new);
            $return = json_decode($return, true);
            // halt($return);
            if (isset($return['errors']) && !empty($return['errors'])) {
                echo "新增订单接口错误" . PHP_EOL;
                continue;
            }else{
                echo "新增订单成功".$return['order']['id'].PHP_EOL;
                $executedCountsu++;
            }

            $update['BackupStatus'] = 1;
            Db::name('order')->where('order_id',$order_id)->update($update);

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,成功'.$executedCountsu.'条当前第' .$i.'页' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;

    }

    
    //客服匹配近六个月订单
    public function CustomerOrders(){
        // $date_msg = date('Y年m月', strtotime('-1 month'));
        // $start_time = date('Y-m-01', strtotime('-1 month'));
        // $end_time = strtotime(date("Y-m-d", strtotime("$start_time +1 month"))) - 1;
        // $start_time = strtotime($start_time);
        // halt($date_msg);

        $where = [];
        $where[]  = ['financial_status', '=',"paid"];
        $where[]  = ['fulfillment_status', '=', "fulfilled"];
        $where[]  = ['createtime', '>=', 1735660800];
        $where[]  = ['createtime', '<=', 1746028800];
        $where[]  = ['disputeapi_status',"=",'暂无争议'];
        // $where[]  = ['id',"<",1185530];
        // $where[]  = ['id',"<",1351135];//临时
        
        $count =  Db::name('order_achievement')
            ->where($where)
            ->count();
        // halt($count);

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('id,order_id,tracking_number,name,fulfillment_status,shop_id,createtime,total_price,sku,skuquantity')
                ->where($where)
                ->order('id','desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();

            $shop_names     = Db::name('shops')->field('id,name')->select()->toArray();
            $shop_names_map = array_column($shop_names,'name','id');
                
            foreach ($list['data'] as $v){
                $order_fulfillments = Db::name('order_fulfillments')->where('order_id',$v['order_id'])->order('created_at asc')->find();
                $order_customer = Db::name('order_customer')->where('order_id',$v['order_id'])->find();
                // $customer_id = $order_customer['customer_id'] ?? 0;
                // $customer_count = Db::name('order_customer')
                //     ->alias('a')
                //     ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
                //     ->where('a.customer_id',$customer_id)
                //     ->where('b.createtime',">=",1704038400)
                //     ->where('b.createtime',"<=",1735660800)
                //     ->count();
                // if($customer_count == 0){
                //     echo "该客户在2024年无订单" . PHP_EOL;
                //     $executedCount++;
                //     $num = $count - $executedCount;
                //     echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条--'.$v['id'] . PHP_EOL;
                //     continue;
                // }
                
                $v['fahuo'] = $order_fulfillments['created_at'] ?? "";
                $v['shop_id'] = $shop_names_map[$v['shop_id']] ?? "";
                $v['email'] = $order_customer['email'] ?? "";
                $v['customer'] = $order_customer['first_name'].$order_customer['last_name'];
                $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                // halt($v);
                Db::name('test_customer')->insert($v);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条--'.$v['id'] . PHP_EOL;
            }
        }
    }

    
    //客服匹配近六个月订单
    public function CustomerOrders2(){
        $where = [];
        $where[] = ['con', '=', 0];
        $count =  Db::name('test_customer')
            ->where($where)
            ->count();

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('test_customer')
                ->where($where)
                ->order('id','desc')
                ->limit($pageSize)
                ->select()
                ->toArray();
                
            foreach ($list as $v){
                $conversations = [];
                if(!empty($v['email'])){
                    $conversations = db::name('conversations')->where('email',$v['email'])->find();
                }
                if(!empty($conversations)){
                    $con = 1;
                }else{
                    $con = 2;
                }
                $update = [
                    'con' => $con,
                ];
                Db::name('test_customer')->where('id',$v['id'])->update($update);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
    }

    

    
    //产品大码--添加上PLUS标签
    public function AddPlusLabel(){
        $where = [];
        $count =  Db::name('test_plussku')
            ->where($where)
            ->count();
        // halt($count);

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('test_plussku')
                ->where($where)
                ->order('id','desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
                
            foreach ($list['data'] as $v){
                $v['sku'] = trim($v['sku']);
                // halt($v);
                $where = [];
                $where[]  = ['a.financial_status', '=',"paid"];
                $where[]  = ['a.createtime', '>=', 1704038400];
                $where[]  = ['a.createtime', '<=', time()];
                $where[]  = ['b.sku', '=', $v['sku']];
                // halt($where);
                $order = Db::name('order_achievement')
                    ->field('a.shop_id,a.createtime,a.order_id,b.sku')
                    ->alias('a')
                    ->join('qu_order_info b','b.order_id = a.order_id', 'left')
                    ->where($where)
                    ->group('a.order_id')
                    ->select()
                    ->toarray();
                    // ->count();
                    // halt($order);
                // halt($v);
                Db::name('test_plusorder')->insertAll($order);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条--' . PHP_EOL;
            }
        }
    }


    
    //去重
    public function AddPlusLabels(){
        $where = [];
        $where[] = ['con', '=', 0];
        $where[] = ['shop_id', '=', 17];
        $count =  Db::name('test_plusorder')
            ->where($where)
            ->count();
        // halt($count);

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('test_plusorder')
                ->where($where)
                ->order('id','desc')
                ->limit($pageSize)
                ->select()
                ->toArray();
                
            foreach ($list as $v){
                $order_customer = Db::name('order_customer')
                    ->field('shop_id,customer_id')
                    ->where('order_id',$v['order_id'])
                    ->find();
                if(!empty($order_customer)){ 
                    $test_pluslabe = Db::name('test_pluslabe')
                        ->where('shop_id',$order_customer['shop_id'])
                        ->where('customer_id',$order_customer['customer_id'])
                        ->find();
                    if(empty($test_pluslabe)){ 
                        $insert = [
                            'shop_id' => $order_customer['shop_id'],
                            'customer_id' => $order_customer['customer_id'],
                        ];
                        Db::name('test_pluslabe')->insert($insert);
                        $executedCountsu++;
                    }
                }
                Db::name('test_plusorder')->where('id',$v['id'])->update(['con' => 1]);
                $executedCount++;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '成功:' . $executedCountsu . '条--' . PHP_EOL;
            }
        }
    }
    
    //产品大码--添加上PLUS标签
    public function AddPlusLabel2(){
        $shop_info = Db::name('shops')->where('id', 17)->find();

        $where = [];
        $where[] = ['con', '=', 0];
        $count =  Db::name('test_pluslabe')
            ->where($where)
            ->count();

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('test_pluslabe')
                ->where($where)
                ->order('id','desc')
                ->limit($pageSize)
                ->select()
                ->toArray();
                
            foreach ($list as $v){
                $customer_id        = $v['customer_id'];
                //打标签
                $url = $shop_info['myshopify_domain'] ."/admin/api/2023-07/customers/".$customer_id.".json";
                // halt($url);
                $return = HttpUtil::getUrl($url,$shop_info);
                // halt($return);
                $tags        = $return['customer']['tags'] ?? "";
                $tags = !empty($tags) ? $tags . ",PLUS" : "PLUS";
                $data = [
                    'customer' => [
                        'id' => $customer_id,
                        'tags' => $tags,
                    ],
                ];
                // halt($url);
                $return = HttpUtil::PutUrl($url, $data, $shop_info);
                // halt($return);
                $executedCount++;
                Db::name('test_pluslabe')->where('id',$v['id'])->update(['con' => 1]);
                echo "总共".$count."条，客户：".$customer_id."执行".$executedCount."条，" . PHP_EOL;
            }
        }
    }

    
    //更新退款订单
    public function UpdateRefundOrder(){
        $t1       = microtime(true);

        list($date,$date_msg,$start_time, $end_time) = $this->SearchMonth();
        
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time];
        $where[]  = ['financial_status', 'in', ["partially_refunded"]];
        // halt($where);
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('id,order_id,old_total_price')
                ->where($where)
                ->limit($pageSize)
                ->order('id desc')
                ->select()
                ->toArray();
                // halt($list);
                
            foreach ($list as $v){
                $refund_amount = Db::name('order_transactions')
                    ->field('Sum(amount) as refund_amount')
                    ->where('order_id',$v['order_id'])
                    ->where('status',"success")
                    ->where('kind',"refund")
                    ->select()->toarray();
                $refund_amount = $refund_amount[0]['refund_amount'] ?? 0;

                $update = [
                    'old_total_price' => $v['old_total_price'],
                    'refund' => $refund_amount,
                    'total_price'   => number_format($v['old_total_price'] - $refund_amount,2),
                ];
                if($update['total_price'] < 0){
                    $update['total_price'] = 0;
                }
                // halt($update);
                Db::name('order_achievement')->where('id',$v['id'])->update($update);
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "更新退款订单-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }


    
    /**
    * @desc    智哥对账
    * @author  zhangheng
    */
    public function Hualei_Check1()
    {
        // $update = Db::name('checkbill_qqwy')
        //     ->where('reconciliation_status',3)
        //     ->update([
        //         'reconciliation_status' => 0,
        //     ]);
        // halt($update);
        $count = Db::name('checkbill_qqwy')
            ->where('reconciliation_status',0)
            ->count();
        echo "筛选查轨迹".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $pageSize = 500;
        $page     = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $subsegment = Db::name('checkbill_qqwy')
                ->field('id,waybill_no,reconciliation_status')
                ->where('reconciliation_status',0)
                ->order('id asc')
                ->limit(500)
                ->select()->toarray();
            foreach ($subsegment as $k=>$v) {
                $executedCount++;
                
                $number = $v['waybill_no'];
                //方法1
                // $result = $this->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$number);
                // $resultData = json_decode($result['result'], true);
                // $trackingContent = $resultData[0]['data'][0] ?? "";
                // if (!empty($trackingContent)) {
                //     $update = [
                //         'trackContent' => $trackingContent['trackContent'] ?? "无数据",
                //         'info' => $trackingContent['businessStatus'] ?? "无数据",
                //         'reconciliation_status' => 2,
                //     ];
                //     Db::name('checkbill_qqwy')->where('id',$v['id'])->update($update);
                //     $executedCountsu++;
                // }else{
                //     $update = [
                //         'reconciliation_status' => 3,
                //     ];
                //     Db::name('checkbill_qqwy')->where('id',$v['id'])->update($update);
                // }

                //方法2
                $order_track = Db::name('order_track')->where('track_number',$number)->find();
                // halt($order_track);
                if(empty($order_track)){
                    $data = array();
                    $data['trackNum'] = $number;
                    $data2[] = $data;
                    $url = "https://apigetway.track718.net/v2/tracking/query";
                    $return = HttpUtil::trackPostUrl718($url, $data2);
                    // halt($return);
                    
                    $track_info = $return['data']['list'] ?? [];
                    $order_track = [];
                    $order_track['latest_status'] = $track_info[0]['latest']['status'] ?? "运输中";
                    // halt($order_track);

                    $message = $return['data']['errors'][0]['message'] ?? "";
                    if (!empty($message)) {
                        if ($message == "Express order number does not exist") {
                            (new ApiOrderLogic())->sync_track_register_718($number);
                            echo "正在注册物流轨迹，请稍后再试" . PHP_EOL;
                        }else{
                            echo "物流API查询错误：".$message . PHP_EOL;
                        }
                    }
                }
                if (!empty($order_track)) {
                    $update = [
                        'trackContent' => $order_track['latest_status'] ?? "",
                        'info' => $order_track['latest_status'] ?? "",
                        'reconciliation_status' => 2,
                    ];
                    Db::name('checkbill_qqwy')->where('id',$v['id'])->update($update);
                    $executedCountsu++;
                }else{
                    $update = [
                        'reconciliation_status' => 3,
                    ];
                    Db::name('checkbill_qqwy')->where('id',$v['id'])->update($update);
                }
                echo "当前第".$i."页，总共".$count."条，物流号：".$v['waybill_no']."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }
    /**
    * @desc    智哥对账
    * @author  zhangheng
    */
    public function Hualei_Check2()
    {
        // $count = Db::name('checkbill_qqwy')
        //     ->where('info','=',"正在注册")
        //     ->update(['reconciliation_status'=>3]);
        $count = Db::name('checkbill_qqwy')
            ->where('reconciliation_status',3)
            ->count();
        echo "筛选查轨迹".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $pageSize = 500;
        $page     = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $subsegment = Db::name('checkbill_qqwy')
                ->field('id,waybill_no,reconciliation_status')
                ->where('reconciliation_status',3)
                ->order('id asc')
                ->limit(500)
                ->select()->toarray();
            foreach ($subsegment as $k=>$v) {
                $executedCount++;

                $number = $v['waybill_no'];
                $order_track = Db::name('order_track')->where('track_number',$number)->find();
                if(!empty($order_track)){
                    $status = $order_track['latest_status'];
                }else{
                    //方法2 查17track
                    $CheckbillLogic = new CheckbillLogic();
                    $status = $CheckbillLogic->trackLogisticsTrajectory($number);
                }
                // halt($status);
                $trackingContent['businessStatus'] = $status ?? "";
                // halt($trackingContent);
                if (!empty($trackingContent)) {
                    $update = [
                        'info' => $status ?? "无数据",
                        'reconciliation_status' => 4,
                    ];
                    Db::name('checkbill_qqwy')->where('id',$v['id'])->update($update);
                    $executedCountsu++;
                }else{
                    $update = [
                        'reconciliation_status' => 5,
                    ];
                    Db::name('checkbill_qqwy')->where('id',$v['id'])->update($update);
                }
                //方法2 查17track

                echo "当前第".$i."页，总共".$count."条，物流号：".$v['waybill_no']."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }

    /**
    * @desc    华磊系统API
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function Hualei_Check()
    {
        // $update['status'] = 0;
        // $count = Db::name('check_hualei')
        //     ->where('status',3)
        //     ->where('info',null)
        //     ->update($update);
        // halt($count);
        $count = Db::name('check_hualeis')
            ->where('status',0)
            ->count();
        echo "筛选查轨迹".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $pageSize = 500;
        $page     = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $subsegment = Db::name('check_hualeis')
                ->field('id,waybill_no,status')
                ->where('status',0)
                ->order('id asc')
                ->limit(500)
                ->select()->toarray();
            foreach ($subsegment as $k=>$v) {
                if($v['status'] !== 0 && $v['status'] !== 3){
                    echo "已执行过" . PHP_EOL;
                    continue;
                }
                $executedCount++;
                
                $number = $v['waybill_no'];
                //方法1
                $result = $this->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$number);
                $resultData = json_decode($result['result'], true);
                $trackingContent = $resultData[0]['data'][0] ?? "";
                // halt($trackingContent);
                if (!empty($trackingContent)) {
                    $update = [
                        'trackContent' => $trackingContent['trackContent'] ?? "无数据",
                        'info' => $trackingContent['businessStatus'] ?? "无数据",
                        'status' => 2,
                    ];
                    if($update['info'] == "签收"){
                        $update['status'] = 4;
                    }
                    // halt($update);
                    Db::name('check_hualeis')->where('id',$v['id'])->update($update);
                    $executedCountsu++;
                }else{
                    $update = [
                        'status' => 3,
                    ];
                    Db::name('check_hualeis')->where('id',$v['id'])->update($update);
                }
                //方法1

                //方法2 查17track
                // $CheckbillLogic = new CheckbillLogic();
                // $status = $CheckbillLogic->trackLogisticsTrajectory($number);
                // // halt($status);
                // $trackingContent['businessStatus'] = $status ?? "";
                // if (!empty($trackingContent)) {
                //     $update = [
                //         'infos' => $status ?? "无数据",
                //         'status' => 4,
                //     ];
                //     Db::name('check_hualeis')->where('id',$v['id'])->update($update);
                //     $executedCountsu++;
                // }else{
                //     $update = [
                //         'status' => 3,
                //     ];
                //     Db::name('check_hualeis')->where('id',$v['id'])->update($update);
                // }
                //方法2 查17track

                echo "当前第".$i."页，总共".$count."条，物流号：".$v['waybill_no']."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }
    
    

    /**
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function px_Check()
    {
        // $update['status'] = 0;
        // $count = Db::name('check_hualei')
        //     ->where('status',3)
        //     ->where('info',null)
        //     ->update($update);
        // halt($count);
        $count = Db::name('check_4px')
            ->where('status',0)
            ->count();
        echo "筛选查轨迹".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $pageSize = 500;
        $page     = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $subsegment = Db::name('check_4px')
                ->field('id,waybill_no,status')
                ->where('status',0)
                ->order('id asc')
                ->limit(500)
                ->select()->toarray();
            foreach ($subsegment as $k=>$v) {
                if($v['status'] !== 0 && $v['status'] !== 3){
                    echo "已执行过" . PHP_EOL;
                    continue;
                }
                $executedCount++;
    
                $params = [
                    'track_number' => $v['waybill_no'],
                ];
                // try
                try {
                    $res    =  (new CheckLogic())->track_4px($params);
                } catch (\Throwable $e) {
                    echo "修改失败". PHP_EOL;  
                    continue;
                }
                $trackingContent = $res['data'];
                $trackDetails = $trackingContent['trackingList'] ?? "";
                $businessStatus = '';
                if (!empty($trackDetails)) {
                    foreach ($trackDetails as $key => $value) {
                        if(empty($businessStatus)){
                            $businessStatus = $value['trackingContent'];
                        }else{
                            break;
                        }
                    }
                }
                if (!empty($businessStatus)) {
                    $update = [
                        'info' => $businessStatus ?? "无数据",
                        'status' => 4,
                    ];
                    Db::name('check_4px')->where('id',$v['id'])->update($update);
                    $executedCountsu++;
                }else{
                    $update = [
                        'status' => 3,
                    ];
                    Db::name('check_4px')->where('id',$v['id'])->update($update);
                }
                echo "当前第".$i."页，总共".$count."条，物流号：".$v['waybill_no']."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }
    
    /**
    * @desc    采购入库相差
    */
    public function DailyQuantity()
    {
        $where = [];
        // $where[] = ['spu',"=",'bra157'];
        //匹配开始
        $count = Db::name('feishu_purchase')  
            ->where($where) 
            ->group('spu')
            ->count();
        if($count < 1){
            echo  "没有数据";die;
        }
        Db::name('feishu_daily_quantity')->where('id',"<>",0)->delete();
        $executedCount = 0;
        $feishu_purchase = Db::name('feishu_purchase')  
            ->where($where) 
            ->group('spu')
            ->select()->toArray();
        foreach ($feishu_purchase as $k => $v) {  
            $purchases = Db::name('feishu_purchase')  
                ->where('spu',$v['spu']) 
                ->where('num',">",0) 
                ->where('status',"=",0) 
                ->select()->toArray();
            if(empty($purchases)) {
                continue;
            }
            $spu = trim($v['spu']);

            $InTransit = 0;
            $Purchases = 0;
            $Delivery = 0;
            $insert_logs = [];
            foreach ($purchases as $key => $value) { 
                $Purchases += (int)$value['num'];
                if(!empty($value['delivery_time'])){
                    $delivery_time = strtotime($value['delivery_time']);
                    //大于当前时间
                    if($delivery_time <= time()){
                        $Delivery += (int)$value['num'];
                    }else{
                        $InTransit += (int)$value['num'];
                    }
                }else{
                    $InTransit += (int)$value['num'];
                }
                $insert_log = [
                    'spu' => $spu,
                    'type' => "采购",
                    'create_time' => $value['create_time'],
                    'num' => $value['num'],
                    'delivery_time' => $value['delivery_time'],
                ];
                $insert_logs[] = $insert_log;
            }
            if(!empty($insert_logs)){
                Db::name('feishu_daily_quantityinfo')
                    ->where('spu',$spu)
                    ->where('type','采购')
                    ->delete();
                Db::name('feishu_daily_quantityinfo')->insertAll($insert_logs);
            }
            //入库数量
            $Inventory = 0;
            $warehouse_entry = Db::name('feishu_warehouse_entry')
                ->field('create_time,sum(num) as num')
                ->where('spu',$spu)
                ->group('create_time')
                ->select()->toarray();
            //入库log
            $insert_warehouses = [];
            foreach ($warehouse_entry as $key => $value) { 
                $Inventory += $value['num'];
                $insert_warehouse = [
                    'spu' => $spu,
                    'type' => "入库",
                    'create_time' => $value['create_time'],
                    'num' => $value['num'],
                ];
                $insert_warehouses[] = $insert_warehouse;
            }
            if(!empty($insert_warehouses)){
                Db::name('feishu_daily_quantityinfo')
                    ->where('spu',$spu)
                    ->where('type','入库')
                    ->delete();
                Db::name('feishu_daily_quantityinfo')->insertAll($insert_warehouses);
            }
            //相差
            $PhaseDifference = (int)$Delivery - (int)$Inventory;
            $insert = [
                'spu' => $spu,
                'InTransit' => $InTransit,
                'Purchases' => $Purchases,
                'Delivery' => $Delivery,
                'Inventory' => $Inventory,
                'PhaseDifference' => $PhaseDifference,
                'UpdateTime' => date('Y-m-d H:i:s'),
            ];

            Db::name('feishu_daily_quantity')->insert($insert);
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----当前SPU'.$spu . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }
    
    /**
    * @desc    根据spu查采购成本--人民币
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function SpuProcurement($spu = '')
    {
        //用最新的采购成本
        $spucost = Db::name('ordercheck_spucost')
            ->where('spu', $spu)
            ->where('material',">",0)
            ->order('timedate desc')
            ->find(); 
        $material = $spucost['material'] ?? 0;
        return $material;
    }
    
    
    
    /**
    * @desc    传sku得到当天销量
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function SalesDetails($spu = '')
    {
        if(empty($spu)){
            return [];
        }
        $where = [];
        $yesterday = date('Y-m-d', time() - timezone());
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
        $where[]  = ['c.createtime', '>=', $midnightYesterday];
        $where[]  = ['c.createtime', '<=', $endOfYesterday]; 
        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['a.spu', 'in', $spu];
        // halt($where);
        
        $lists = Db::name('order_skuinfo')
            ->field('
                sum(a.realcount) as skuquantity,
                a.spu,a.new_sku
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->group('spu')
            ->where($where)
            ->select()->toarray();
        return $lists;
    }
    

    
    
    /**
    * @desc    传spu查半年所有尺码
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function SpuToCheckAll($spu = 'bra183')
    {
        if(empty($spu)){
            return [];
        }
        $where = [];
        $where[]  = ['c.createtime', '>=', time() - 3600*24*90];
        $where[]  = ['c.createtime', '<=', time()]; 
        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['a.spu', '=', $spu];
        // halt($where);
        
        $lists = Db::name('order_skuinfo')
            ->field('
                a.new_sku
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->group('a.new_sku')
            ->where($where)
            ->select()->toarray();
        $lists = array_column($lists, 'new_sku');

        $sizeOrder = [
            'S', 'S/M', 'XS/S', 'XS', 'M', 'M/L', 'L', 'L/XL', 'XL',
            'XL/2XL', '2XL', '3XL', '3XL/4XL', '4XL', '5XL', '6XL'
        ];
        $new_skus = [];
        $type = "";
        foreach ($lists as $key => $value) { 
            if(strpos($value, '-')){
                $current_info = explode('-', $value);
                $size = $current_info[2] ?? "";
                if(in_array($size, $sizeOrder)){
                    $new_sku = [
                        'color' => $current_info[1] ?? "",
                        'size' => $size,
                        'cup' => "",
                    ];
                    $type = "size";
                }else{
                    $new_sku = [
                        'color' => $current_info[1] ?? "",
                        'size' => "",
                        'cup' => $size,
                    ];
                    $type = "cup";
                }
            }
            if(!empty($new_sku)){
                $new_skus[] = $new_sku;
            }
        }
        // halt($type);
        if($type == 'cup'){
            $new_skus =(new PlanSuggestLogic())->sort_cup($new_skus);
        }
        if($type == 'size'){
            $new_skus =(new PlanSuggestLogic())->sort_size($new_skus);
        }
        halt($new_skus);
        return $new_skus;
    }

    

    //手动更新
    public function ManuallyUpdateAdv()
    {
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];

        for($num = 53; $num <= 85; $num++){
            $start_time = date('Y-m-d', time() - 3600*24*$num);
            $this->integrated_get_fb($start_time,$token);
            echo PHP_EOL . "完成更新,日期".$start_time . PHP_EOL;
        }
    }

    
    public function integrated_get_fb($date_start,$token){

        $advertiser_id = '648376641121073';

        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        
        $url = $path.'act_'.$advertiser_id.'/insights?access_token='.$token.'&fields=account_id,impressions,spend,website_purchase_roas,cpc,cpm&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        // halt($return);

        if (!empty($return['data']) && isset($return['data'])) {
            foreach ($return['data'] as $ka=>$va) {
                $insert = [];
                $insert['stat_time'] = strtotime($date_start);
                $insert['stat_time_day'] = date('Y-m-d H:i:s',strtotime($date_start));
                $insert['advertiser_id'] = $advertiser_id;
                $insert['platform_id'] = 1;
                $insert['impressions'] = $va['impressions'];
                $insert['spend'] = $va['spend'];
                $insert['roas'] = $va['website_purchase_roas'][0]['value'] ?? "";
                $insert['cpc'] = $va['cpc'] ?? 0;
                $insert['cpm'] = $va['cpm'] ?? 0;
                $insert['type_name'] = "API";
                $insert['spend'] = $va['spend'];
                $insert['createtime'] = time();
                
                $advertising_info = Db::name('advertising')
                    ->where('advertiser_id', $insert['advertiser_id'])
                    ->where('stat_time_day', date('Y-m-d H:i:s',strtotime($date_start)))
                    ->find();
                if(!empty($advertising_info)){
                    Db::name('advertising')->where('id',$advertising_info['id'])->update($insert);
                }
            }
        }
        return true;
    }

    //自动发货
    public function automaticShippings()
    {
        $t1       = microtime(true);
        
        $where[]  = ['status', '=', 0];
        $where[]  = ['waybill_no', '=', ""];
        $count = Db::name('tik_auto_shipping')
            ->where($where)
            ->count();
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('tik_auto_shipping')
                ->where($where)
                ->limit($pageSize)
                ->order('id asc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                //自动发货
                $return = $this->automaticShipping($v);
                if($return['error'] == "T"){
                    Db::name('tik_auto_shipping')
                        ->where('id',$v['id'])
                        ->update([
                            'status' => 1,
                            'deliver_no' => $return['deliver_no'] ?? "",
                            'error' => $return['content'] ?? "",
                            'update_time' => date('Y-m-d H:i:s'),
                        ]);
                }else{
                    Db::name('tik_auto_shipping')
                        ->where('id',$v['id'])
                        ->update([
                            'status' => 3,
                            'deliver_no' => $return['deliver_no'] ?? "",
                            'error' => $return['content'] ?? "",
                            'update_time' => date('Y-m-d H:i:s'),
                        ]);
                }
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "自动发货-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
     * 自动发货
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function automaticShipping($order)
    {
        if(!empty($order['sku'])){
            $skus = explode(",",$order['sku']);
            foreach ($skus as $sku){
                $deliver_products[] = [
                    "sku" => $sku,
                    "nums" => 1
                ];
            }
        }else{
            $deliver_products = [];
        }

        $deliver_no = $order['deliver_no'] ?? "";
        if(empty($deliver_no)){
            //毫秒时间戳
            $deliver_no = time() . rand(1000, 9999);
        }
        //  update 2025-08-07;
        $warehouse_id =  $order['warehouse_id'] ?? "3";
        $token        =  Config('Logisticskey.YiJT.token');
        $ck_nums      =  Config('Logisticskey.YiJT.ck_nums');
        $chqd         =  Config('Logisticskey.YiJT.chqd');
        if($warehouse_id == 4){
            $ck_nums      =  Config('Logisticskey.YiJT.ck_nums2');
            $chqd         =  Config('Logisticskey.YiJT.chqd2');
        }

        $JsonDatas = [
            [
                //固定内容
                "country"  => "美国",
                "ck_nums"  => $ck_nums,
                "token"    => $token,
                "chqd"     => $chqd,
                "platform" => "shopify",
                
                //自定义内容
                "contact" => $order['contact'] ?? "",
                "deliver_no" => $deliver_no,
                "deliver_products" => $deliver_products,
                "mobile" => $order['mobile'] ?? "",
                "phone" => $order['mobile'] ?? "",
                "address" => $order['address'] ?? "",
                "city" => $order['city'] ?? "",      
                "district" => $order['district'] ?? "",
                "zip" => $order['zip'] ?? "",
                "email" => $order['email'] ?? "",
            ]
        ];
        // halt($JsonDatas);
        $url = Config('Logisticskey.YiJT.url');
        //订单数据推送到易境通 2024-12-07
        $url = $url . Config('Logisticskey.YiJT.add_order');
        $response = HttpUtil::postUrlYiJT($url, $JsonDatas);
        $result   = json_decode($response, true);
        htmlLog(['params'=>$JsonDatas,'response'=>$response],OPERATE_LOG . date('Ym') . '/tik_automaticShipping/' . date('Ymd') . '.txt');
        $result['deliver_no'] = $deliver_no;
        return $result;
    }

    
    //回传物流单号
    public function tracking_number_update_tk()
    {
        $t1       = microtime(true);
        
        $where[]  = ['status', '=', 1];
        $where[]  = ['waybill_no', '=', ""];
        $count = Db::name('tik_auto_shipping')
            ->where($where)
            ->count();
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('tik_auto_shipping')
                ->where($where)
                ->limit($pageSize)
                ->order('id asc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                //自动发货
                $return = $this->tracking_number_update_tkinfo($v);
                // halt($return);
                if(!empty($return)){
                    //注册718
                    (new ApiOrderLogic())->sync_track_register_718($return);
                    
                    Db::name('tik_auto_shipping')
                        ->where('id',$v['id'])
                        ->update([
                            'status' => 2,
                            'waybill_no' => $return,
                            'update_time' => date('Y-m-d H:i:s'),
                        ]);
                        $executedCountsu++;
                }
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '成功:' . $executedCountsu . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "回传物流单号-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
     * @desc    回传物流单号
     */
    public function tracking_number_update_tkinfo($order){
        //替换成易境通
        $url =Config('Logisticskey.YiJT.url') . Config('Logisticskey.YiJT.hwc_order');
        $JsonDatas = [
            'token'      => Config('Logisticskey.YiJT.token'),
            'deliver_no' => $order['deliver_no'] ?? "",
        ];
        $response = HttpUtil::postUrlYiJT($url,$JsonDatas);
        $result   = json_decode($response, true);
        $result = $result['data'][0] ?? [];
        $Wt_LogisticsOrderNo  = $result['waybill']??'';
        // echo '物流单号'.$Wt_LogisticsOrderNo .PHP_EOL;
        return $Wt_LogisticsOrderNo;
    }


    /**
     * @desc   获取在线表格数据
     * @author luckyXiong
     * @date   2024-10-24
     */
    public function getTablerecordsPants($params=[]){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_table_list');
        $table_id              = $params['table_id']??'tblVJOBE35a9nqmr';
        $table_token           = $params['table_token']??'U3RNbtIeUaGlRWsnevgcyjUQngg';
        if(!$table_id){
            echo 'table_id不能为空!';
            return true;
        }
        $token                 = self::get_app_access_token();
        $url                   = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                   = HttpUtil::getFeiShu($url,$token,[]);
        // halt($res);
        if($res['code']==0){
            $list = $res['data']['items'];
            echo "总共".count($list)."条数据". PHP_EOL;
            $arr = [];
            foreach($list as $v){
                    $info = $v['fields'];
                    if(!isset($info['发货SKU']) || !$info['发货SKU']) continue;
                    $values =  self::change_data($info);
                    if($values){
                        $arr[] = $values;
                    }
            }
            // halt($arr);
            //数据批量存入库
            if($arr){
                // Db::name('feishu_purchase')->where('id',"<>",0)->delete();
                Db::name('tik_auto_shipping')->insertAll($arr);
            }
            echo "完成". PHP_EOL;
        }else{
            echo "无数据". PHP_EOL;
        }
    }

    
    /**
     * @desc   整理数据格式
     * @author luckyXiong
     * @date   2024-10-25
     */
    private function change_data($info=[]){
        $create_time     = $info['日期']??"";
        if(!empty($create_time)){
            $create_time = date('Y-m-d H:i:s',$create_time/1000);
        }
        $spu = $info['发货SKU']??'';
        $spus = explode("\n",$spu);
        $spus_new = [];
        foreach ($spus as $key => $value) {
            if(empty(trim($value))){
                continue;
            }
            $spus_new[] = trim($value);
        }
        $spus = implode(",",$spus_new);
        // halt($spus);
        $data =  [
            'sku'                   => $spus,
            'created_time'           => $create_time,
            'update_time'           => $create_time,
            'contact'         => $info['收件人姓名']??'',
            'deliver_no'         => $info['小店订单号']??'',
            'mobile'         => $info['电话']??'',
            'address'         => $info['详细地址']??'',
            'city'         => $info['省份']??'',
            'district'         => $info['市区']??'',
            'zip'         => $info['邮编']??'',
            'type'         => 1,
        ];
        // halt($data);
        $res = Db::name('tik_auto_shipping')
            ->where('deliver_no',$data['deliver_no'])
            ->find();
        if($res){
            echo "已存在". PHP_EOL;
            return [];
        }else{
            return  $data;
        }
    }
    


    /**
     * @desc   获取app_token
     * @author xx
     * @date 2024-09-24
     */
    public function get_app_access_token(){
        $key        = "app_access_token_feishu";
        $token      = Cache::store('redis')->get($key);
        if(empty($token)){
            $app_id                = Config('Logisticskey.fei_shu.app_id');
            $app_secret            = Config('Logisticskey.fei_shu.app_secret');
            $basic_url             = Config('Logisticskey.fei_shu.basic_url');
            $app_access_token_url  = Config('Logisticskey.fei_shu.app_access_token');
            $url                   = $basic_url.$app_access_token_url;
            $data                  = [
                'app_id'    => $app_id,
                'app_secret'=> $app_secret,
            ];
            $response = HttpUtil::postDataCurl($url, $data);
            $token    = $response['app_access_token']??'';
            $expire   = $response['expire']??'';
            Cache::store('redis')->set($key, $token,$expire-3);
        }
        return  $token;
    }

    

    //4px平台物流轨迹API
    public function Logistics4px()
    {
        $tracking_number = '4PX';
        $count = Db::name('order_achievement')
            ->where('createtime','>=',strtotime('-3 month'))
            ->where('tracking_number',"like","%{$tracking_number}%")
            ->where('fulfillment_status',"fulfilled")
            ->count();
        echo PHP_EOL . "总计:" . $count . '条' . PHP_EOL;
        // halt($count);
        $pageSize = 600;
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;

        for ($i = 0; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('id,order_id,tracking_number,createtime,shop_id')
                ->where('createtime','>=',strtotime('-3 month'))
                ->where('tracking_number',"like","%{$tracking_number}%")
                ->where('fulfillment_status',"fulfilled")
                ->order('createtime desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
                foreach ($list['data'] as $k => $v) {
                    $executedCount++;

                    $params = [];
                    $params['track_number'] = $v['tracking_number'];
                    // try
                    try {
                        $res    =  (new CheckLogic())->track_4px($params);
                        $executedCountsu++;
                    } catch (\Throwable $e) {
                        echo "修改失败". PHP_EOL;  
                        continue;
                    }
                    // halt($res);
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '条,成功'.$executedCountsu.'条' . PHP_EOL;
                }
        }
    }


    
    /**
    * @desc    给客户打标签--hwc
    * @author  zhangheng
    */
    public function LabelCustomershwc()
    {
        $count = Db::name('order_achievement')
            ->alias('a')
            ->join('qu_order_customer b','b.order_id = a.order_id', 'left')
            ->where('a.tags',"LIKE",'%hwc%')
            ->where('a.createtime',">=",1748707200)
            ->where('a.createtime',"<=",time())
            ->where('a.shipment_status',"LIKE",'%delivered%')
            ->where('a.shop_id',17)
            ->group('b.customer_id')
            ->count();
        // halt($count);
        echo "给客户打标签".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $customers = Db::name('order_achievement')
            ->alias('a')
            ->field('a.order_id,a.shop_id,b.customer_id')
            ->join('qu_order_customer b','b.order_id = a.order_id', 'left')
            ->where('a.tags',"LIKE",'%hwc%')
            ->where('a.createtime',">=",1748707200)
            ->where('a.createtime',"<=",time())
            ->where('a.shipment_status',"LIKE",'%delivered%')
            ->where('a.shop_id',17)
            ->group('b.customer_id')
            ->order('a.id desc')
            ->select()->toarray();
            
            $shop_id        = 17;
            $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
            foreach ($customers as $k=>$customer) {
                $customer_id        = $customer['customer_id'];
                //打标签
                $url = $shop_info['myshopify_domain'] ."/admin/api/2023-07/customers/".$customer_id.".json";
                $return = HttpUtil::getUrl($url,$shop_info);
                // halt($return);
                $tags        = $return['customer']['tags'] ?? "";
                $tags = !empty($tags) ? $tags . ",hwc1" : "hwc1";
                $data = [
                    'customer' => [
                        'id' => $customer_id,
                        'tags' => $tags,
                    ],
                ];
                // halt($url);
                $return = HttpUtil::PutUrl($url, $data, $shop_info);
                // halt($return);
                echo "总共".$count."条，客户：".$customer_id."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
    }

    
    
    /**
    * @desc    给客户打标签--SignFor
    * @author  zhangheng
    */
    public function LabelCustomersSignFor()
    {
        // shopify`.`qu_order_tracklog` WHERE `latest_status` LIKE '%收货%' AND `shopify_status` LIKE '%delivered%'
        $count = Db::name('order_tracklog')
            ->alias('a')
            ->join('qu_order_customer b','b.order_id = a.order_id', 'left')
            ->where('a.latest_status',"=",'收货')
            ->where('a.shopify_status',"=",'delivered')
            ->group('b.customer_id')
            ->count();
        // halt($count);
        echo "给客户打标签".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $customers = Db::name('order_tracklog')
            ->alias('a')
            ->field('a.order_id,a.shop_id,b.customer_id')
            ->join('qu_order_customer b','b.order_id = a.order_id', 'left')
            ->where('a.latest_status',"=",'收货')
            ->where('a.shopify_status',"=",'delivered')
            ->group('b.customer_id')
            ->select()->toarray();
            foreach ($customers as $k=>$customer) {
                $shop_id        = $customer['shop_id'];
                $shop_info      = Db::name('shops')->where('id',$shop_id)->find();

                $customer_id        = $customer['customer_id'];
                //打标签
                $url = $shop_info['myshopify_domain'] ."/admin/api/2023-07/customers/".$customer_id.".json";
                $return = HttpUtil::getUrl($url,$shop_info);
                // halt($return);
                $tags        = $return['customer']['tags'] ?? "";
                $tags = !empty($tags) ? $tags . ",delivery email" : "delivery email";
                $data = [
                    'customer' => [
                        'id' => $customer_id,
                        'tags' => $tags,
                    ],
                ];
                // halt($url);
                $return = HttpUtil::PutUrl($url, $data, $shop_info);
                // halt($return);
                echo "总共".$count."条，客户：".$customer_id."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
    }

    /**
    * @desc    给客户打标签--Whatever
    * @author  zhangheng
    */
    public function LabelCustomersWhatever()
    {
        $count = Db::name('order_achievement')
            ->alias('a')
            ->where('a.tags',"LIKE",'%hwc%')
            ->where('a.createtime',">=",1746028800)
            ->where('a.createtime',"<=",time())
            ->where('a.shipment_status',"LIKE",'%delivered%')
            ->where('a.shop_id',17)
            ->count();
        // halt($count);
        echo "给客户打标签".$count . PHP_EOL;
        // halt($count);
        $executedCount = 0;
        $executedCountsu = 0;

        $customers = Db::name('order_achievement')
            ->alias('a')
            ->field('a.order_id,a.shop_id')
            ->where('a.tags',"LIKE",'%hwc%')
            ->where('a.createtime',">=",1746028800)
            ->where('a.createtime',"<=",time())
            ->where('a.shipment_status',"LIKE",'%delivered%')
            ->where('a.shop_id',17)
            ->order('a.id desc')
            ->select()->toarray();
            
            $shop_id        = 17;
            $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
            foreach ($customers as $k=>$customer) {
                $order_id        = $customer['order_id'];
                //打标签
                $url = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id.".json";
                $tags = !empty($tags) ? $tags . ",Whatever" : "Whatever";
                $data = [
                    'order' => [
                        'id' => $order_id,
                        'tags' => $tags,
                    ],
                ];
                // halt($url);
                $return = HttpUtil::PutUrl($url, $data, $shop_info);
                // halt($return);
                echo "总共".$count."条，订单：".$order_id."执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
    }

    
    
    //转单号元字段----修改带引号的
    public function ConversionNumber(){
        $shop_id        = 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();

        $where = [];
        $where[]  = ['createtime', '>=', 1748707200];
        $where[]  = ['createtime', '<=', time()];
        $where[]  = ['fulfillment_status', '=', "fulfilled"];
        $where[]  = ['tracking_number_new', '<>',''];
        $where[]  = ['tracking_number', 'like', "%DYY%"];
        $where[]  = ['shop_id', '=',17];
        // $where[]  = ['order_id', '=',7146931618162];
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $lists = Db::name('order_achievement')
                ->field('id,order_id,tracking_number,tracking_number_new')
                ->where($where)
                ->limit(500)
                ->order('createtime asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
        
            foreach($lists['data'] as $k=>$v){
                $tracking_number_new = $v['tracking_number_new'] ?? "";
                //开始修改元子段
                $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$v['order_id']."/metafields.json";   
                $return = HttpUtil::getUrl($url,$shop_info);
                // halt($return);
                $old_value = $return['metafields'][0]['value'] ?? "";
                $old_id = $return['metafields'][0]['id'] ?? 0;
                if(!empty($old_value)){
                    if(strpos($old_value,'"') !== false){ 
                        //修改元字段
                        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$v['order_id']."/metafields/".$old_id.".json";   
                        $post = array();
                        $post['metafield']['namespace'] = 'custom';
                        $post['metafield']['key'] =  '_zhuandanhao';
                        $post['metafield']['value'] = $tracking_number_new;
                        $post['metafield']['type'] = 'single_line_text_field';
                        // halt($post);
                        $return = HttpUtil::PutUrl($url,$post, $shop_info);
                        $return = json_decode($return, true);
                        $executedCountsu++;
                    }
                }
                // halt($return);
                $executedCount++;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '成功'.$executedCountsu.'条，当前:'.$v['order_id'].',第' .$i.'页' . PHP_EOL;
            }
        }
    }

    
    
    //转单号元字段
    public function ConversionNumberElementField(){
        $shop_id        = 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();

        $where = [];
        $where[]  = ['createtime', '>=', 1748707200];
        $where[]  = ['createtime', '<=', time()];
        $where[]  = ['fulfillment_status', '=', "fulfilled"];
        $where[]  = ['tracking_number_new', '=',''];
        $where[]  = ['tracking_number', 'like', "%DYY%"];
        $where[]  = ['shop_id', '=',17];
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $lists = Db::name('order_achievement')
                ->field('id,order_id,tracking_number')
                ->where($where)
                ->limit(500)
                ->order('createtime asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
        
            foreach($lists['data'] as $k=>$v){
                $tracking_number = $v['tracking_number'] ?? "";
                // halt($tracking_number);

                //查询转单号
                $result = $this->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$tracking_number);
                $resultData = json_decode($result['result'], true);
                $tracking_number_new = $resultData[0]['data'][0]['business_channeltransfercode'] ?? "";
                if(empty($tracking_number_new)){
                    $executedCount++;
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '成功'.$executedCountsu.'条，当前:'.$tracking_number.',转单号:'.$tracking_number_new.',第' .$i.'条' . PHP_EOL;
                    continue;
                }
                // halt($tracking_number_new);
                //开始打元子段
                $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$v['order_id']."/metafields.json";   

                $post = array();
                $post['metafield']['namespace'] = 'custom';
                $post['metafield']['key'] =  '_zhuandanhao';
                $post['metafield']['value'] = $tracking_number_new;
                $post['metafield']['type'] = 'single_line_text_field';
                // halt($post);
                $return = HttpUtil::PostUrl($url,$post, $shop_info);
                $return = json_decode($return, true);
                if(!empty($return['errors']) || !empty($return['error'])){
                    $update = [];
                    $update['tracking_number_new'] = $tracking_number_new;
                    Db::name('order_achievement')
                        ->where('id',$v['id'])
                        ->update($update);
                    echo PHP_EOL . '转单号:'.$tracking_number_new.'API错误' . PHP_EOL;
                    halt($return['errors']);
                }else{
                    $update = [];
                    $update['tracking_number_new'] = $tracking_number_new;
                    Db::name('order_achievement')
                        ->where('id',$v['id'])
                        ->update($update);
                    $executedCountsu++;
                }
                $executedCount++;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '成功'.$executedCountsu.'条，当前:'.$tracking_number.',转单号:'.$tracking_number_new.',第' .$i.'条' . PHP_EOL;
            }
        }
    }

    
    //物流轨迹时效
    public function orderValidity(){
        $where = [];
        // $where[] = ['latest_time', '=', null];
        $where[] = ['OrderTime', '=', null];
        $where[] = ['DeliveredTime', '=', null];
        // $where[] = ['id', '=', 1062854];
        // $where[] = ['track_number', '=', "DYY666765114XB"];
        $where[] = ['platform_track', '=', 1];
        $where[] = ['update_time', '>=', "2025-08-09"];
        // $where[] = ['AbnormalState', '=', 0];

        // $count =  Db::name('order_track')
        //     ->where($where)
        //     ->count();
        //     // ->update([
        //     //     'AbnormalState' => 4,
        //     // ]);
        // halt($count);

        $count =  Db::name('order_track')
            ->where($where)
            ->count();
        // halt($count);

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_track')
                ->field('id,track_number,tracking_list,platform_track,latest_status,latest_time')
                ->where($where)
                ->order('latest_time asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
                
            foreach ($list as $v){
                // halt($v);
                
                $order = Db::name('order_fulfillments')
                    ->field('a.tracking_number,a.created_at as DeliveryTime,b.createtime as OrderTime,b.name')
                    ->alias('a')
                    ->join('qu_order_achievement b','b.order_id = a.order_id', 'left')
                    ->where('a.tracking_number',$v['track_number'])
                    ->find();
                if(!empty($order)){
                    $DeliveryTime = $this->dateTimeStr($order['DeliveryTime']); 
                    if($order['DeliveryTime'] > 0){
                        $order['DeliveryTime'] = date('Y-m-d H:i:s',$DeliveryTime);
                    }
                    if($order['OrderTime'] > 0){
                        $order['OrderTime'] = date('Y-m-d H:i:s',$order['OrderTime']);
                    }

                    $track_list = $v['tracking_list'] ? json_decode($v['tracking_list'],true) : [];
                    if(!empty($track_list)){
                        switch ($v['platform_track']) {
                            case '1':
                                $track_list = $this->track_lists($track_list,$DeliveryTime);
                                break;
                            case '2':
                                break;
                            default:
                        }
                    }
                    // halt($order);
                    $update = [
                        'order_number' => $order['name'] ?? "",
                        'order_id' => $order['order_id'] ?? "",
                        'OrderTime' => $order['OrderTime'] ?? 0,
                        'DeliveryTime' => $order['DeliveryTime'] ?? 0,
                        'SurfInternet' => $track_list['SurfInternet'] ?? 0,
                        'Domestic' => $track_list['Domestic'] ?? 0,
                        'AcceptCarriage' => $track_list['AcceptCarriage'] ?? 0,
                        'Foreign' => $track_list['Foreign'] ?? 0,
                        'SignFor' => $track_list['SignFor'] ?? 0,
                        'msg' => $track_list['msg'] ?? "",
                        'AbnormalState' => $track_list['AbnormalState'] ?? 0,
                        'latest_time' => date("Y-m-d H:i:s"),
                    ];
                    if($v['latest_status'] == 'Delivered'){
                        $update['DeliveredTime'] = $track_list['time_raw_new'];
                        $update['AbnormalState'] = 0;
                    }
                    // halt($update);
                    Db::name('order_track')
                        ->where('id',$v['id'])
                        ->update($update);
                    $executedCountsu++;
                }else{
                    $update = [
                        'latest_time' => date("Y-m-d H:i:s"),
                    ];
                    Db::name('order_track')
                        ->where('id',$v['id'])
                        ->update($update);
                }
                $executedCount++;
                echo "总共".$count."条，当前".$v['track_number'].",时间:".$v['latest_time'].",执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }


    
    //重新邮件订阅
    public function ResendEmailSubscription(){
        $shop_info = Db::name('shops')->where('id',17)->find();

        $where = [];
        $where[] = ['created_at', '>=', "2025-01"];
        $where[] = ['email_state', '<>', "subscribed"];
        $where[] = ['email_state_type', '=', 0];
        $where[] = ['shop_id', '=', 17];

        $count =  Db::name('order_customer')
            ->where($where)
            ->count();
        // halt($count);

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_customer')
                ->field('id,customer_id')
                ->where($where)
                ->order('created_at desc')
                ->limit($pageSize)
                ->select()
                ->toArray();
                
            foreach ($list as $v){
                // halt($v);
                $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/customers/".$v['customer_id'].".json";
                $return = HttpUtil::getUrl($url, $shop_info);
                // halt($return);
                $email_state = $return['customer']['email_marketing_consent']['state'] ?? "";
                if($email_state == "not_subscribed" || $email_state == "unsubscribed"){
                    //重新订阅
                    $customer_tags = $return['customer']['tags'] ?? ""; //原始标签
                    $new_tags = "Resubscribed";
                    if(!empty($customer_tags)){
                        //如果customer_tags不包含sms20241118则添加
                        if(strpos($customer_tags, $new_tags) === false){
                            $tags_new = $customer_tags . "," . $new_tags;
                        }else{
                            $tags_new = $customer_tags; 
                        }
                    }else{
                        $tags_new = $new_tags;
                    }
                    $tags_new = array_unique(explode(",", $tags_new));
                    $post = [];
                    $post['customer']['tags'] = $tags_new;
                    $post['customer']['phone'] = $return['customer']['phone'] ?? "";
                    if(empty($post['customer']['phone'])){
                        $post['customer']['phone'] = $return['customer']['addresses'][0]['phone'] ?? "";
                    }
                    // 客户订阅
                    $post['customer']['id'] = $v['customer_id'];
                    $post['customer']['accepts_marketing'] = true;
                    $post['customer']['accepts_marketing_updated_at'] = '2025-08-08T00:09:10-07:00';
                    $post['customer']['email_marketing_consent']['state'] = 'subscribed';
                    $post['customer']['email_marketing_consent']['opt_in_level'] = $return['customer']['sms_marketing_consent']['opt_in_level'] ?? "single_opt_in";
                    // $post['customer']['sms_marketing_consent']['state'] = 'subscribed';
                    // $post['customer']['sms_marketing_consent']['opt_in_level'] = $return['customer']['sms_marketing_consent']['opt_in_level'] ?? "single_opt_in";

                    $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/customers/".$v['customer_id'].".json";
                    $return = HttpUtil::puturl($url,$post,$shop_info);
                    // halt($return);
                    if (!empty($return['errors'])) {
                        $update = [
                            'email_state' => $email_state,
                            'email_state_type' => 2,
                            'accepts_marketing' => "错误",
                        ];
                        Db::name('order_customer')
                            ->where('id',$v['id'])
                            ->update($update);
                        $executedCountsu++;
                    }else{
                        $update = [
                            'email_state' => "subscribed",
                            'email_state_type' => 1,
                            'accepts_marketing' => "自动订阅成功",
                            'phone' => $post['customer']['phone'] ?? "",
                            'tags' => implode(",", $post['customer']['tags']),
                        ];
                        Db::name('order_customer')
                            ->where('id',$v['id'])
                            ->update($update);
                        $executedCountsu++;
                    }
                }else{
                    $update = [
                        'email_state' => $email_state,
                        'email_state_type' => 3,
                    ];
                    Db::name('order_customer')
                        ->where('id',$v['id'])
                        ->update($update);
                }
                $executedCount++;
                echo "总共".$count."条，当前".$v['customer_id'].",状态:".$email_state.",执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }

    
    //物流轨迹时效---手动更新未上网
    public function orderValidityNot(){
        $where = [];

        $where[] = ['OrderTime', '>', 0];
        $where[] = ['update_time', '>=', "2025-08-09"];
        $where[] = ['platform_track', '=', 1];
        $where[] = ['AbnormalState', '=', 1];
        // $where[] = ['track_number', '=', "DYY012665477XB"];

        $count =  Db::name('order_track')
            ->where($where)
            ->count();
        // halt($count);

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_track')
                ->field('id,track_number,tracking_list,platform_track,latest_status,latest_time,DeliveryTime')
                ->where($where)
                ->order('latest_time asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            foreach ($list as $v){
                $order_number = $v['track_number'];
                $data = (new ApiOrderLogic())->sync_track_info_718($order_number);
                // halt($data);
                $post = $data['data'] ?? [];
                if(!empty($post)){
                    $list               = $post['list'][0]['fromDetail']??[];
                    $status_sub_arr     = Config('Logisticskey.718_info.sub_status_key');
                    $status_arr         = Config('Logisticskey.718_info.status_key');
                    $status_17_staus    = Config('Logisticskey.718_info.718_17_status');
                    //最新的物流主状态;
                    $subResult          =  $post['list'][0]['latest']['subResult']??'';
                    $result             =  $post['list'][0]['latest']['result']??'';
                    $latest_status      =  $status_arr[$result]??'';
                    $latest_status      =  $status_17_staus[$latest_status]??'';
                    //最新物流子状态;
                    $latest_sub_status  =  $status_sub_arr[$subResult]??'';

                    //tracking数组;
                    $tracking_info             = [];
                    $tracking_list             = $list;

                    if($tracking_list){
                        foreach($tracking_list as $v){
                            $temp['time_raw']    = $v['date'];
                            $temp['location']    = '';
                            $temp['description'] = $v['status'];
                            $temp['sub_status']  = $status_sub_arr[$v['subResult']]??'';
                            $tracking_info[]     = $temp;
                        }
                    }
                    $update_data = [
                        'latest_status'    =>$latest_status,
                        'latest_sub_status'=>$latest_sub_status,
                        'platform_track'   =>1,
                        'tracking_list'    =>$tracking_info ? json_encode($tracking_info) : '',
                        'update_time'      =>date("Y-m-d H:i:s", time()),
                    ];
                    // halt($order_number);
                    Db::name('order_track')->where('track_number',$order_number)->update($update_data);
                    //更新订单表物流在途状态
                    Db::name('order')
                        ->where('tracking_number', $order_number)
                        ->update(['LogisticsStatus' => $latest_status]);
                    Db::name('order_achievement')
                        ->where('tracking_number', $order_number)
                        ->update(['LogisticsStatus' => $latest_status]);
                    $executedCountsu++;
                }
                $executedCount++;
                echo "总共".$count."条，当前".$order_number.",执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }


    
    //物流轨迹时效---快速识别是否超时
    public function orderValidityTimedOut(){
        $where = [];
        $where[] = ['DeliveredTime', '=', null];
        $where[] = ['OrderTime', '>', 0];
        $where[] = ['update_time', '>=', "2025-08-09"];
        $where[] = ['platform_track', '=', 1];
        // $where[] = ['track_number', '=', "DYY012665477XB"];

        $count =  Db::name('order_track')
            ->where($where)
            ->count();
        // halt($count);

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_track')
                ->field('id,track_number,tracking_list,platform_track,latest_status,latest_time,DeliveryTime')
                ->where($where)
                ->order('latest_time asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
                
            foreach ($list as $v){
                $v['DeliveryTime'] = strtotime($v['DeliveryTime']);
                $track_list = $v['tracking_list'] ? json_decode($v['tracking_list'],true) : [];
                if(!empty($track_list)){
                    switch ($v['platform_track']) {
                        case '1':
                            $track_list = $this->track_lists($track_list,$v['DeliveryTime']);
                            break;
                        case '2':
                            break;
                        default:
                    }
                }
                // halt($order);
                $update = [
                    'SurfInternet' => $track_list['SurfInternet'] ?? 0,
                    'Domestic' => $track_list['Domestic'] ?? 0,
                    'AcceptCarriage' => $track_list['AcceptCarriage'] ?? 0,
                    'Foreign' => $track_list['Foreign'] ?? 0,
                    'SignFor' => $track_list['SignFor'] ?? 0,
                    'msg' => $track_list['msg'] ?? "",
                    'AbnormalState' => $track_list['AbnormalState'] ?? 0,
                    'latest_time' => date("Y-m-d H:i:s"),
                ];
                if($v['latest_status'] == 'Delivered'){
                    $update['DeliveredTime'] = $track_list['time_raw_new'];
                    $update['AbnormalState'] = 0;
                }
                // halt($update);
                Db::name('order_track')
                    ->where('id',$v['id'])
                    ->update($update);
                $executedCountsu++;
                $executedCount++;
                echo "总共".$count."条，当前".$v['track_number'].",时间:".$v['latest_time'].",执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }


    
    //物流轨迹时效---物流断更手动更新
    public function LogisticsManualUpdate(){
        $where = [];
        $where[] = ['DeliveredTime', '=', null];
        $where[] = ['OrderTime', '>', 0];
        $where[] = ['update_time', '>=', "2025-08-09"];
        $where[] = ['platform_track', '=', 1];
        $where[] = ['AbnormalState', 'in', [1,2]];
        // $where[] = ['track_number', '=', "DYY012665477XB"];

        $count =  Db::name('order_track')
            ->where($where)
            ->count();
        // halt($count);

        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_track')
                ->field('id,track_number,tracking_list,platform_track,latest_status,latest_time,DeliveryTime')
                ->where($where)
                ->order('latest_time asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
                
            foreach ($list as $v){
                
                $data = array();
                $data['trackNum'] = $v['track_number'] ?? "";
                $data2[] = $data;
                $url = "https://apigetway.track718.net/v2/tracking/query";
                $return = HttpUtil::trackPostUrl718($url, $data2);
                // halt($return);
                
                $track_info = $return['data']['list'] ?? [];

                $message = $return['data']['errors'][0]['message'] ?? "";
                if (!empty($message)) {
                    if ($message == "Express order number does not exist") {
                        (new ApiOrderLogic())->sync_track_register_718($data['trackNum']);
                        echo $data['trackNum']."正在注册物流轨迹，请稍后再试" . PHP_EOL;
                    }else{
                        echo "物流API查询错误：".$message . PHP_EOL;
                    }
                    $executedCount++;
                    echo "总共".$count."条，当前".$v['track_number'].",时间:".$v['latest_time'].",执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
                    continue;
                }

                if(!empty($track_info)){
                    $order_track = [];
                    $order_track['latest_status'] = $track_info[0]['latest']['status'] ?? "运输中";
                    $order_track['latest_sub_status'] = $track_info[0]['latest']['status'] ?? "运输中";
                    $order_track['provider_name'] = $track_info[0]['code']??'USPS';
                    $order_track['provider_country'] = $track_info[0]['country']??'US';
                    $order_track['receive_country'] = $track_info[0]['country']??'US';
                    $order_track['tracking_list'] = $track_info ?? [];
                    Db::name('order_track')
                        ->where('id',$v['id'])
                        ->update($order_track);
                    $executedCountsu++;
                }
                
                $executedCount++;
                echo "总共".$count."条，当前".$v['track_number'].",时间:".$v['latest_time'].",执行".$executedCount."条，成功".$executedCountsu."条" . PHP_EOL;
            }
        }
    }


    /**
    * @desc    track_lists
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function track_lists($track_list,$DeliveryTime)
    {
        // halt($track_list);
        $data = [
            'SurfInternet' => 0,
            'Domestic' => 0,
            'AcceptCarriage' => 0,
            'SignFor' => 0,
        ];
        $msg = '';
        foreach ($track_list as $k=>$v){
            $description = $v['description'] ?? '';
            //签收成功
            if(strpos($description,'Delivered') !== false || strpos($description,'DELIVERED') !== false){
                $data['SignFor'] = $v['time_raw'];
                if(!empty($data['SignFor'])){
                    $msg = $msg . "已签收时间：".$data['SignFor'] . PHP_EOL;
                    $data['SignFor'] = strtotime($data['SignFor']);
                }
            }
            //本地物流承运
            if(strpos($description,'Delivery to local courier') !== false){
                $data['AcceptCarriage'] = $v['time_raw'];
                if(!empty($data['AcceptCarriage'])){
                    $msg = $msg . "本地物流承运时间：".$data['AcceptCarriage'] . PHP_EOL;
                    $data['AcceptCarriage'] = strtotime($data['AcceptCarriage']);
                }
            }
            //到达目的地国
            if(strpos($description,'Flight Arrived') !== false){
                $data['Domestic'] = $v['time_raw'];
                if(!empty($data['Domestic'])){
                    $msg = $msg . "达到目的地时间：".$data['Domestic'] . PHP_EOL;
                    $data['Domestic'] = strtotime($data['Domestic']);
                }
            }
            //已上网
            if(strpos($description,'到达收货点') !== false || strpos($description,'Arrived at export center') !== false){
                $data['SurfInternet'] = $v['time_raw'];
                if(!empty($data['SurfInternet'])){
                    $msg = $msg . "已上网时间：".$data['SurfInternet'] . PHP_EOL;
                    $data['SurfInternet'] = strtotime($data['SurfInternet']);
                }
            }
            //包裹退回
            if(strpos($description,'returned') !== false || strpos($description,'Return') !== false){
                $AbnormalState3 = 1;
            }
            //投递失败
            if(strpos($description,'failed to be delivered') !== false){
                $AbnormalState4 = 1;
            }

        }
        if($DeliveryTime > 0){
            $msg = $msg . "已发货时间：".date('Y-m-d H:i:s',$DeliveryTime) . PHP_EOL;
        }
        // halt($msg);
        // halt($data);
        $AbnormalState = 0;
        // 上网
        if($DeliveryTime > 0 && $data['SurfInternet'] > 0){
            //两个时间戳差 计算成天数
            $SurfInternet = floor(($data['SurfInternet'] - $DeliveryTime) / (24 * 3600));
        }else{
            $SurfInternet = 0;
        }
        
        // 国内运输
        if($data['Domestic'] > 0 && $data['SurfInternet'] > 0){
            //两个时间戳差 计算成天数
            $Domestic = floor(($data['Domestic'] - $data['SurfInternet']) / (24 * 3600));
        }else{
            $Domestic = 0;
        }
        // 承运
        if($data['AcceptCarriage'] > 0 && $data['Domestic'] > 0){
            //两个时间戳差 计算成天数
            $AcceptCarriage = floor(($data['AcceptCarriage'] - $data['Domestic']) / (24 * 3600));
        }else{
            $AcceptCarriage = 0;
        }
        // 国外运输
        if($data['SignFor'] > 0 && $data['AcceptCarriage'] > 0){
            //两个时间戳差 计算成天数
            $Foreign = floor(($data['SignFor'] - $data['AcceptCarriage']) / (24 * 3600));
        }else{
            $Foreign = 0;
        }
        //AbnormalState类型
        $AbnormalState = 0;
        $time_raw = $track_list[0]['time_raw'] ?? "";
        $time_raw_new = $time_raw;
        if(!empty($time_raw)){
            $time_raw = strtotime($time_raw);
            if((time() - $time_raw) > 86400 * 5){
                $AbnormalState = 2;//物流断更
            }
            if((time() - $DeliveryTime) > 86400 * 3){
                $description = $track_list[0]['description'] ?? '';
                //超时未上网
                if(strpos($description,'货物电子信息已经收到') !== false || strpos($description,'Shipment information received') !== false || strpos($description,'Parcel information received') !== false || empty($description)){
                    $AbnormalState = 1;//超时未上网
                }
            }
        }
        if(isset($AbnormalState3) && $AbnormalState3 == 1){
            $AbnormalState = 3;
        }
        if(isset($AbnormalState4) && $AbnormalState4 == 1){
            $AbnormalState = 4;
        }
        // halt($AbnormalState);
        // 签收
        if($data['SignFor'] > 0 && $DeliveryTime > 0){
            //两个时间戳差 计算成天数
            $SignFor = floor(($data['SignFor'] - $DeliveryTime) / (24 * 3600));
            $AbnormalState = 0;
        }else{
            $SignFor = 0;
        }
        $data = [
            'SurfInternet' => $SurfInternet ?? 0,
            'Domestic' => $Domestic ?? 0,
            'AcceptCarriage' => $AcceptCarriage ?? 0,
            'Foreign' => $Foreign ?? 0,
            'SignFor' => $SignFor ?? 0,
            'msg' => $msg,
            'AbnormalState' => $AbnormalState ?? 0,
            'time_raw_new' => $time_raw_new ?? "",
        ];
        // halt($data);
        return $data;
    }
    

    /**
    * @desc    删除折扣
    * @author  zhangheng
    */
    public function DeleteDiscount()
    {
        $shop_id        = 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $return = $this->DeleteDiscounts($shop_info,0,1);
        halt($return);
    }

    /**
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function DeleteDiscounts($shop_info,$ControlUpdateTime,$page)
    {
        $page++;

        $limit = 50;

        date_default_timezone_set('Asia/Shanghai');

        if(!empty($ControlUpdateTime)){
            $created_at_max = $ControlUpdateTime;
        }else{
            // $created_at_max1 = date('Y-m-d', time());
            // $created_at_max2 = date('H:i:s', time());
            // $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-07:00';
            // $created_at_max = '2025-08-16';//
            // $created_at_max = '2025-06-08T22:59:59-07:00';//13w
            $created_at_max = '2025-04-23T10:01:10-07:00';//35w
            $created_at_max = '2025-04-22T10:01:40-07:00';//2w
            $created_at_max = '2025-04-08T10:01:59-07:00';//12w
            $created_at_max = '2025-03-09T09:04:20-08:00';//30w
            $created_at_max = '2025-03-02T07:00:07-08:00';//10w
            $created_at_max = '2025-02-24T09:00:28-08:00';//18w
            $created_at_max = '2025-02-10T06:43:22-08:00';//20w
            $created_at_max = '2025-02-07T09:04:02-08:00';//3w
            $created_at_max = '2025-01-31T09:04:18-08:00';//13w
            $created_at_max = '2025-01-19T09:06:16-08:00';//20w
            $created_at_max = '2025-01-09T11:01:37-08:00';//20w
        }
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version."/price_rules.json";

        //拉取历史
        $url = $url . '?created_at_max=' . $created_at_max . '&limit=' . $limit;
        $return = HttpUtil::getUrl($url, $shop_info);
        if (!empty($return['errors'])) {
            halt($return);
        }
        $return = $return['price_rules'] ?? [];
        if(empty($ControlUpdateTime)){
            $ControlUpdateTime = "";
        }
        foreach ($return as $k=>$v) {
            $title = $v['title'] ?? '';
            echo "当前折扣码：".$title . PHP_EOL;
            if(!empty($ControlUpdateTime)){
                $createtime = $this->dateTimeStr($v['created_at']);
                $ControlUpdateTimeTimeStamp = $this->dateTimeStr($ControlUpdateTime);
                if($ControlUpdateTimeTimeStamp > $createtime){
                    $ControlUpdateTime = $v['created_at'];
                }
            }else{
                $ControlUpdateTime = $v['created_at'];
            }
            $ends_at = $v['ends_at'] ?? "";
            if(!empty($ends_at)){
                $ends_ats = $this->dateTimeStr($ends_at);
                if(time() > $ends_ats && $ends_ats > 1){
                    //删除
                    echo "开始删除--折扣码已过期--过期时间".$ends_at . PHP_EOL;
                    $id = $v['id'] ?? 0;
                    $return = $this->DeleteDiscountsinfo($shop_info,$id);
                }
            }

        }
        echo "完成--当前页：".$page ."当前时间".$ControlUpdateTime. PHP_EOL;
        if(!empty($ControlUpdateTime)){
            //今年已执行完成
            $ControlUpdateTimes = $this->dateTimeStr($ControlUpdateTime);
            if($ControlUpdateTimes >= 1 && $ControlUpdateTimes <= 1735660800){
                echo "今年已执行完成" . PHP_EOL;
                return true;
            }
            $return = $this->DeleteDiscounts($shop_info,$ControlUpdateTime,$page);
        }
        return true;
    }

    /**
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function DeleteDiscountsinfo($shop_info,$id)
    {
        if(empty($id)){
            echo "id不能为空";
            return true;
        }
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version."/price_rules/".$id.".json";
        $return = HttpUtil::delUrl($url, $shop_info);
        return true;
    }
    

    //skuinfo添加颜色尺码
    public function order_skuinfo(){
        $t1       = microtime(true);

        $count = Db::name('order_skuinfo')
            ->where('createtime',">=",1735660800)
            ->where('cup',"=","")
            ->where('spu',"like","%bra%")
            ->group('new_sku')
            ->count();
        // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        $executedCountsu = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_skuinfo')
                ->field('id,new_sku as sku,spu')
                // ->where('id',"=",1001863)
                ->where('createtime',">=",1735660800)
                ->where('cup',"=","")
                ->where('spu',"like","%bra%")
                ->group('new_sku')
                ->order('id asc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                $seller_sku   = $v['sku']??'';
                $product_type = 1;
                $sizeinfo     = (new PlanSuggestLogic())->get_size($seller_sku,$product_type);
                if(!empty($sizeinfo['color'])){
                    $update['color'] = $sizeinfo['color'] ?? "";
                    $update['size'] = $sizeinfo['size'] ?? "";
                    $update['cup'] = $sizeinfo['cup'] ?? "";
                    Db::name('order_skuinfo')
                        ->where('new_sku',$v['sku'])
                        ->update($update);
                    $executedCountsu++;
                }else{
                    continue;
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . ',成功'.$executedCountsu.'条,剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }
    

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function test3()
    {
        $where[] = ['createtime', '>=', 1704038400];
        $where[] = ['createtime', '<=', 1735660800];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[] = ['is_seel', '<>',1];
        $where[] = ['spu', 'like',"%bra%"];
        $lists = Db::name('order_skuinfo')
            ->field('
            DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m") as date,
            sum(a.realcount) as quantity,spu')
            ->alias('a')
            ->group('date,spu')  
            ->where($where)
            ->order(['date' => 'asc','quantity' => 'desc'])
            ->select()  
            ->toArray();
        foreach ($lists as &$v) {
            $sku_price = self::get_spu_price_info($v['spu']);
            $v['price'] = '$'.getRes($sku_price*$v['quantity']);
        }
        DB::name('test4')->insertAll($lists);
        echo "完成" . PHP_EOL;
    }

    


    /**
     * @desc    获取spu单价
     * @date    2024/8/22
     * @author  luckyXiong
     */
    public function get_spu_price_info($spu=''){
        $key   = "spu_price_single";
        $list  = Cache::store('redis')->get($key);
        if(!$list){
            $list = Db::name('order_spu_price')->field('spu,price')->select()->toArray();
            Cache::store('redis')->set($key,$list,86400*7);
        }

        $list_map   = array_column($list,null,'spu');

        $price_info = $list_map[$spu]??[];

        $price      = $price_info['price']??'28.26';
        return $price;
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function test4()
    {
        $where = [];
        $where[] = ['a.createtime', '>=', 1735660800];
        $where[] = ['a.createtime', '<=', time()];
        $where[]  = ['a.tags','like','%Master%'];
        $where[]  = ['a.payment_gateway_names', '=',"shopify_payments"];

        $lists = Db::name('order_achievement')
            ->field('
            a.shop_id,a.name,a.order_id,a.financial_status,
            a.fulfillment_status,
            a.payment_gateway_names,
            a.refund,a.tags,
            a.old_total_price,
            a.total_price,
            a.currency,
            a.total_price,
            a.sku,
            b.name as shop_name,
            c.created_at,c.updated_at,c.closed_at
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->join('qu_order c','c.order_id = a.order_id', 'left')
            ->where($where)
            ->order('a.shop_id desc,c.created_at desc')
            ->select()
            ->toarray();
        Db::name('test4')->insertAll($lists);
        // foreach ($lists as $key => $value) {
        //     echo $key ."成功". PHP_EOL;
        // }
        echo "完成". PHP_EOL;
        die;

        $where = [];
        $where[]  = ['createtime', '>=', 1753977600];
        
        $shops = Db::name('shops')->field('id,name')->select()->toarray();
        $shop_map = array_column($shops,'name','id');
            
        $tables = [
            'order_dispute_afterpay',
            'order_dispute_airwallex',
            'order_dispute_paypal',
            'order_dispute_stripe',
            'order_dispute_api'
        ];
        
        $lists = [];
        foreach ($tables as $table) {
            $list = Db::name($table)
                ->field('tracking_number,fulfillment_status,financial_status,order_name,shop_id,order_id')
                ->where($where)
                ->select()->toarray();
            $lists = array_merge($lists, $list);
        }

        foreach ($lists as $key => $value) {
            $counts = Db::name('order_achievement')
                ->where('order_id',$value['order_id'])
                ->where('tags','like','%Master%')
                ->where('payment_gateway_names',"shopify_payments")
                ->count();
            if($counts > 0){
                $value['payment_gateway_names'] = "shopify_payments";
                $value['shop_name'] = $shop_map[$value['shop_id']];
                // halt($value);
                Db::name('test4')->insert($value);
                echo $key."插入成功" . PHP_EOL;           
            }else{
                echo $key."插入失败" . PHP_EOL;     
            }
        }
    }
    
    /**
    * @desc    检核shopify退款状态与支付平台是否同步
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function CheckbillRefund()
    {
        $where = [];
        $where[] = ['createtime', '>=', 1735660800];
        $where[] = ['createtime', '<=', time()];
        $where[] = ['disputeapi_status',"<>","暂无争议"];
        $where[]  = ['financial_status', '=', "paid"];
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
            // ->select()
            // ->toarray();
        if($count > 0){
            $order_achievement = Db::name('order_achievement')
                ->field('order_id,disputeapi_status')
                ->where($where)
                ->select()
                ->toarray();
                $Abnormal = 0;
            foreach ($order_achievement as $key => $value) {
                switch ($value['disputeapi_status']) {
                    case '争议赢':
                        // echo $key."是争议赢,跳过" . PHP_EOL;
                        break;
                    case '待处理': 
                        // echo $key."是待处理,跳过" . PHP_EOL;
                        break;
                    case '审核中': 
                        // echo $key."是待处理,跳过" . PHP_EOL;
                        break;
                    case '其他': 
                        // echo $key."是待处理,跳过" . PHP_EOL;
                        break;
                    default:
                        halt($value);
                        echo "订单号".$value['order_id']. "的状态是" .$value['disputeapi_status']. PHP_EOL;
                        $Abnormal++;
                        break;
                }
                echo "总共".$count."条数据,异常".$Abnormal."条数据" . PHP_EOL;
            }
        }
        echo "完成". PHP_EOL;
    }
    
}
